package com.jt.www.queue.issue;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.jt.www.admin.user.service.UserService;
import com.jt.www.common.service.MessageService;
import com.jt.www.common.service.SendEmailsService;
import com.jt.www.dao.mapper.issue.EPolicyLogMapper;
import com.jt.www.dao.mapper.issue.EPolicyMapper;
import com.jt.www.dao.mapper.issue.mapper.IssuePolicyLogEntityMapper;
import com.jt.www.dao.mapper.issue.mapper.IssueRecordEntityMapper;
import com.jt.www.dao.mapper.issue.mapper.MqMessageEntityMapper;
import com.jt.www.enums.ErrorCode;
import com.jt.www.enums.issue.*;
import com.jt.www.message.NewElecInvoiceInfoVO;
import com.jt.www.message.NewElecInvoicePrintRequestVO;
import com.jt.www.message.NewElecPolicyInfoList;
import com.jt.www.model.entity.MessageInfoEntity;
import com.jt.www.model.entity.User;
import com.jt.www.model.issue.entity.IssuePolicyLogEntity;
import com.jt.www.model.issue.entity.IssueRecordEntity;
import com.jt.www.model.issue.entity.MqMessageEntity;
import com.jt.www.model.mail.dto.MailDTO;
import com.jt.www.model.param.endorse.AppDetailProParam;
import com.jt.www.model.pay.ResBindDetailQo;
import com.jt.www.model.pay.ResBindQo;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.model.vo.endorse.AppDetailProVo;
import com.jt.www.model.vo.sdCheck.ApplicationFormInvoiceVo;
import com.jt.www.model.vo.sdCheck.AttachmentForProVO;
import com.jt.www.model.vo.sdCheck.HolderForProVO;
import com.jt.www.model.vo.sdCheck.PolAttachmentProVO;
import com.jt.www.queue.systemparametes.ConfigurationParameters;
import com.jt.www.remote.DexClient;
import com.jt.www.remote.ins.InsClient;
import com.jt.www.util.DateUtils;
import com.jt.www.util.JsonUtils;
import com.jt.www.util.MD5Utils;
import com.jt.www.util.SecurityUrl;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.util.StringUtil;

import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;

@Component
public class ElecPolicyMsglistener {

    public static final Logger log = LoggerFactory.getLogger(ElecPolicyMsglistener.class);
    private final static Integer MESSAGE_TYPE = 2;// 投保单
    @Autowired
    EPolicyLogMapper ePolicyLogMapper;
    @Autowired
    EPolicyMapper ePolicyMapper;
    @Autowired
    DexClient dexClient;
    @Autowired
    InsClient insClient;
    @Autowired
    IssueRecordEntityMapper issueRecordEntityMapper;
    @Autowired
    IssuePolicyLogEntityMapper issuePolicyLogEntityMapper;
    @Autowired
    MqMessageEntityMapper mqMessageEntityMapper;
    @Autowired
    private SendEmailsService emailsService;
    @Autowired
    private UserService userService;
    @Autowired
    private ConfigurationParameters configurationParameters;
    @Autowired
    private MessageService messageService;
    // dev环境注释掉  test放开
    @RabbitListener(queues = "${jtpf.rabbit.queuename.epolicy}")
    public void processMsg(Message msg, Channel channel) {
        Long logId = System.currentTimeMillis();

        log.info("{}:ElecPolicyMsglistener get MessageProperties  {}", logId, msg.getMessageProperties().toString());
        log.info("{}:ElecPolicyMsglistener get MessageBody  {}", logId, new String(msg.getBody()));

        byte[] msgbody = msg.getBody();
        if (msgbody == null || msgbody.length == 0) {
            log.info("{}:返回报文为空 {} {}", logId, msg.getMessageProperties().getReceivedExchange(), msg.getMessageProperties().getReceivedRoutingKey());
            try {
                channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                log.error("{}:ACK确认出错，出错信息为", logId, e);
            }
            return;
        }
        try {
            // 字节数组转换为输入流
            InputStream is = new ByteArrayInputStream(msgbody);
            // 解析xml
            SAXReader reader = new SAXReader();
            Document document = reader.read(is);
            Element rootElement = document.getRootElement();
            String ifCode = msg.getMessageProperties().getHeaders().get("IfCode").toString();

            //添加消息记录入库 并直接返回 ack
            MqMessageEntity mqMessageEntity = new MqMessageEntity();
            mqMessageEntity.setIfCode(ifCode);
            mqMessageEntity.setMessage(rootElement.asXML());
            mqMessageEntity.setCreateTime(new Date());
            mqMessageEntityMapper.insert(mqMessageEntity);
            processMqMessage(rootElement, ifCode, logId);
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("{}:ElecPolicyMsglistener出错，出错信息为", logId, ex);
        } finally {
            try {
                channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                log.error("{}:ACK确认出错，出错信息为", logId, e);
            }
        }
    }

    /**
     * 处理消息
     *
     * @param rootElement
     * @param logId
     */
    public void processMqMessage(Element rootElement, String ifCode, Long logId) throws Exception {
        log.info("{}:解析的消息：{}", logId, rootElement.asXML());
        // 保险公司响应的报文
        boolean result = true;
        switch (ifCode) {
            case "20190528001":
            case "20190528002":
            case "20190528003":
                //华泰产品（泰然无忧百万医疗） or  //华泰产品（华泰财险成长护航重疾险）or 华泰产品（华泰财险安康保护伞）
                result = processHT(rootElement, ifCode);
                break;
            case "20190516002":
            case "20190919002":
                //山东产品（山东省校（园）方责任保险项目）
                result = processSD(rootElement, ifCode);
                break;
            case "20190516006":
                //云南非九（校方综合防范保障保险、教职员工校方责任保险、云南省校方责任保险、校园食品安全责任保险）
                result = processYNFJ(rootElement, ifCode);
                break;
            //云南非九新诚泰（校方综合防范保障保险、教职员工校方责任保险、云南省校方责任保险、校园食品安全责任保险）
            case "202010231517560":
                result = processNewYNFJ(rootElement, ifCode);
                break;
            case "20190515002":
            case "20190726012":
                //1实责（全国职业院校学生实习责任保险）  2校责（校方责任保险）
                result = processSZAndXZ(rootElement, ifCode);
                break;
            case "20190515026":
                //学责（学生安全责任保险）
                result = processXZ(rootElement, ifCode);
                break;
            case "20190515006":
            case "20200211001":
            case "20200330006":   //新我学保阳光保护伞(改版之后)
            case "202006171149460":
            case "202008191339340": //山西新学道
                //阳光财产安责保护伞
                result = processAZBHS(rootElement, ifCode);
                break;
            case "20190802002":
                //食品险（校园食品安全责任保险）
                result = processSPX(rootElement, ifCode);
                break;
            case "20190729001":
            case "202008181443590":  //新徐州
                //徐州学平险（徐州学平意外险/徐州监护人责任险）
                result = processXZXPX(rootElement, ifCode);
                break;
            case "20190805001"://济宁学平电子保单 使用统一下载格式
            case "20190807001": //食品险-中华联合电子保单 使用统一下载格式
                result = processEpolicy(rootElement, IssueEnum.getIssueEnum(ifCode));
                break;
            case "20190518001":
                //实责校责（大地）
                result = processSZXZDD(rootElement, ifCode);
                break;
                /*case "20190726012":
                    //实责校责（阳光）
                    result = processXSZAndXZ(rootElement,ifCode);
                    break;*/
            case "20190805002":
                //食品险（阳光）
                result = processSP(rootElement, ifCode);
                break;
            case "20190726017":  //实责校责（太平）
            case "20190731001":   //实责校责（中华联合）
            case "20190827001":  //实责校责 新国寿财
                result = processSZXZ(rootElement, ifCode);
                break;
            case "20190726007":
            case "20190909101":   //国寿财食品
                //食品险（太平）
                result = processSPXTP(rootElement, ifCode);
                break;
            case "202008041342390":
            case "202008180929030":
            case "202008190924410":
            case "202008190922090":
                result = processGD(rootElement, ifCode);
                break;
            case "202008241457160":
                result = processJiNingXPX(rootElement, ifCode);
                break;
            case "202009090116140":
                result = processJiNingXPXOnline(rootElement, ifCode);
                break;
            case "202009171037520":
                result = processQiDong(rootElement, ifCode);
                break;
            default:
                log.error("{}:错误的ifCode {}", logId, ifCode);
        }
        if (!result) {
            //消息入库定时重试5次
        }
    }

    /**
     * 华泰产品(华泰财险成长护航重疾险/华泰财险安康保护伞/泰然无忧百万医疗)
     *
     * @param rootElement
     * @return
     */
    private Boolean processHT(Element rootElement, String ifCode) {
        Element respPacket = getRespPacket(rootElement);
        Element policyURL = respPacket.element("policyURL");
        String reqPacketStr = rootElement.element("reqPacket").getStringValue();

        String currentTime = DateUtils.getCurrentTime();
        // 投保单号
        String tbNo = rootElement.element("ApplicationFormCode").getStringValue();
        // 保单号
        String policyNo = rootElement.element("PolicyNo").getStringValue();
        // 解析险种
        //Map<String, Object> map = JsonUtils.fromJson(reqPacketStr, Map.class);
        //Map<String, Object> insuranceObject = (Map<String, Object>) map.get("insuranceObject");
        String proCode = IssueEnum.getProCodeByIfCode(ifCode);//(String) insuranceObject.get("insuranceCode");
        // 入库
        // 入库之前首先判断 是否已经入库  根据投保单号判断
        IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
        issueRecordEntity.setApplicationFormCode(tbNo);
        List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
        if (select != null && select.size() > 0) {
            log.info("系统时间：" + currentTime + ",[华泰]投保单号是" + tbNo + "的消息发送重复");
            // 消息重复，消息直接消费完成。
            return true;
        }
        issueRecordEntity.setPolicyNo(policyNo);
        issueRecordEntity.setProCode(proCode);
        issueRecordEntity.setReqPacket(reqPacketStr);
        issueRecordEntity.setResPacket(respPacket.asXML());
        issueRecordEntity.setSendStatus("1");

        //0：失败  1：成功； 2 : 订单号重复，返回对应保单信息
        String status = respPacket.element("responseCode").getStringValue();
        if ("1".equals(status)) {
            status = "2";
        } else if ("0".equals(status)) {
            status = "3";
        } else if ("2".equals(status)) {
            status = "4";
        }
        // 数据中心返回 的投保单状态
        issueRecordEntity.setStatus(status);
        issueRecordEntity.setCreateTime(currentTime);
        issueRecordEntity.setUpdateTime(currentTime);
        issueRecordEntity.setIfCode(ifCode);
        issueRecordEntityMapper.insert(issueRecordEntity);
        if ("3".equals(status) || "4".equals(status)) {
            // 出单失败或者重复出单，消息直接消费完成，在入库的逻辑后边。
            return true;
        }
        // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子保单
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";
        issuePolicyLogEntity.setApplicationFormCode(tbNo);
        issuePolicyLogEntity.setPolicyNo(policyNo);
        issuePolicyLogEntity.setType("1");
        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(proCode);
        String url = policyURL.getStringValue();
        // 拼装下载报文
        Document doc = DocumentHelper.createDocument();
        Element info = doc.addElement("body");
        info.addElement("url").addText(url);
        issuePolicyLogEntity.setParam(info.asXML());
        issuePolicyLogEntity.setTimes(0);
        issuePolicyLogEntity.setIfCode(ifCode);
        issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
        // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
        issueRecordEntity.setSendStatus("2");
        issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);

        //调用接口,请求数据交换中心，下载电子保单
        try {
            log.info("我学保华泰的投保单号是 " + tbNo + " 保单下载参数：" + info.asXML());
            // 请求下载保单，成功更新
            String seqNo = Long.toString(Math.abs(new Random().nextLong()));
            ResponseEntity<String> responseEntity = dexClient.text("edu", "20190516022", "1.0", seqNo, info.asXML());
            log.info("我学保华泰的投保单号是  " + tbNo + " 保单下载返回值：" + responseEntity.getStatusCodeValue() + "," + responseEntity.getBody());
            consumeStatus = "2";
            String fileId = responseEntity.getBody();
            issuePolicyLogEntity.setStatus(consumeStatus);
            // 下载成功，更新数据库，绑定资源
            log.info("我学保华泰的投保单号是  下载消息 fileId：{}", fileId);
            bindingResources(tbNo, fileId, issuePolicyLogEntity);
            return true;
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 云南非九新诚泰（校方综合防范保障保险、教职员工校方责任保险、云南省校方责任保险、校园食品安全责任保险）
     *
     * @param rootElement
     * @return
     */
    private Boolean processNewYNFJ(Element rootElement, String ifCode) {
        String currentTime = DateUtils.getCurrentTime();
        // 解析xml，封装数据
        Element reqPacket = getReqPacket(rootElement);
        Element respPacket = getRespPacket(rootElement);
        // 投保单号
        String tbNo = rootElement.element("ApplicationFormCode").getStringValue();
        // 保单号
        String policyNo = rootElement.element("PolicyNo").getStringValue();
        //产品编码
        String productCode = rootElement.element("ProductCode").getStringValue();
        // 入库之前首先判断 是否已经入库  根据投保单号判断
        IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
        issueRecordEntity.setApplicationFormCode(tbNo);
        List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
        if (select != null && select.size() > 0) {
            log.info("系统时间：" + currentTime + ",云南非九投保单号是" + tbNo + "的消息发送重复");
            // 消息重复，消息直接消费完成。
            return true;
        }
        issueRecordEntity.setPolicyNo(policyNo);
        issueRecordEntity.setProCode(productCode);
        issueRecordEntity.setReqPacket(reqPacket.asXML());
        issueRecordEntity.setResPacket(respPacket.asXML());
        issueRecordEntity.setSendStatus("1");

        // 数据中心返回 的投保单状态
        issueRecordEntity.setStatus("2");
        issueRecordEntity.setCreateTime(currentTime);
        issueRecordEntity.setUpdateTime(currentTime);
        issueRecordEntity.setIfCode(ifCode);
        issueRecordEntityMapper.insert(issueRecordEntity);

        // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子保单
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";
        issuePolicyLogEntity.setApplicationFormCode(tbNo);
        issuePolicyLogEntity.setPolicyNo(policyNo);
        issuePolicyLogEntity.setType("1");
        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(productCode);
        String url = getChengtaiPolicy(policyNo, configurationParameters.getPartnerCode(), configurationParameters.getCodeKey());
        // 拼装下载报文
        Document doc = DocumentHelper.createDocument();
        Element info = doc.addElement("Body");
        info.addElement("url").addText(url);
        issuePolicyLogEntity.setParam(info.asXML());
        issuePolicyLogEntity.setIfCode(ifCode);
        issuePolicyLogEntity.setTimes(1);
        issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
        // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
        issueRecordEntity.setSendStatus("2");
        issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);
        //调用接口,请求数据交换中心，下载电子保单
        Boolean flag = false;
        try {
            ResponseEntity<String> responseEntity = null;
            String ebody = null;
            Element ebodyElement = null;
            // 请求下载保单，成功更新
            log.info(DateUtils.getCurrentTime() + "云南非九投保单号是 " + tbNo + " 下载保单开始，入参" + info.asXML());
            String seqNo = Long.toString(Math.abs(new Random().nextLong()));
            try {
                responseEntity = dexClient.text("edu", "20190516016", "1.0", seqNo, info.asXML());
                consumeStatus = "2";
                ebody = responseEntity.getBody();
                log.info(DateUtils.getCurrentTime() + "云南非九投保单号是 " + tbNo + " 下载保单结束，回参" + ebody);
                doc = DocumentHelper.parseText(ebody);
                ebodyElement = doc.getRootElement();
                Element data = ebodyElement.element("data");
                if (data == null) {
                    log.error("云南非九请求下载电子保单失败");
                    issuePolicyLogEntity.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(issuePolicyLogEntity);
                } else {
                    String fileId = data.getStringValue();
                    issuePolicyLogEntity.setStatus(consumeStatus);
                    // 下载成功，更新数据库，绑定资源
                    log.info("云南非九 下载消息 fileId ：{}", fileId);
                    bindingResources(tbNo, fileId, issuePolicyLogEntity);

                }
            } catch (Exception e) {
                e.printStackTrace();
                issuePolicyLogEntity.setTimes(1);
                issuePolicyLogEntity.setStatus("3");
                issuePolicyLogEntityMapper.updateByPrimaryKeySelective(issuePolicyLogEntity);
            }
            sendEmail(tbNo, "021");
            log.info(DateUtils.getCurrentTime() + "诚泰保单号{},生成电子发票开始", policyNo);
            // 下载电子发票 拼装参数
            IssuePolicyLogEntity t = new IssuePolicyLogEntity();
            consumeStatus = "1";
            t.setApplicationFormCode(tbNo);
            t.setPolicyNo(policyNo);
            t.setType("3");
            t.setStatus(consumeStatus);
            t.setCreateTime(currentTime);
            t.setUpdateTime(currentTime);
            t.setProCode(productCode);
            t.setIfCode(ifCode);
            // 组装电子发票的报文
            AppDetailProVo appDetailProVo = insAppDetailList(tbNo);
            String invoiceType = appDetailProVo.getApplicationFormInvoiceVos().get(0).getInvoiceType();
            if (invoiceType.equals(InvoiceTypeEnum.ELECTRONIC_INVOICE.getType())) {
                JSONObject innerObj = new JSONObject();//要用json本身自带的对象声明插入
                innerObj.put("requestType", configurationParameters.getInvoiceRequestType()); //请求类型
                innerObj.put("userName", configurationParameters.getInvoiceUserName());//用户名
                innerObj.put("passWord", configurationParameters.getInvoicePassWord());//密码
                innerObj.put("partnerCode", configurationParameters.getInvoicePartnerCode());//合作伙伴编码
                innerObj.put("queryId", seqNo);//外网提供的唯一标志
                innerObj.put("policyNo", policyNo);//保单号
                innerObj.put("endorNo", "");//批单号
                innerObj.put("appName", appDetailProVo.getHolder().getCorporation().getName());//购方姓名 投保人名称
                innerObj.put("telePhone", appDetailProVo.getHolder().getCorporation().getLinkPhone());//购方联系电话
                innerObj.put("idType", IdTypeEnum.getType(appDetailProVo.getHolder().getCorporation().getThreeInOneCode().length()));//购方证件类型
                innerObj.put("idNumber", appDetailProVo.getHolder().getCorporation().getThreeInOneCode());//购方证件号码
                innerObj.put("taxPayerNo", appDetailProVo.getApplicationFormInvoiceVos().get(0).getTaxpayerIdentificationNumber());//纳税人识别号
                innerObj.put("email", appDetailProVo.getHolder().getCorporation().getEmail());//购方邮箱
                innerObj.put("totalPriceFlag", "0");//显示合计标识
                innerObj.put("riskPrintFlag", "0");//险种合并打印标识
                //根据产品编码映射到保险公司编码
                innerObj.put("riskCode", RiskCodeEnum.getRiskCode(productCode));//riskCode
                innerObj.put("payNo", "1");//缴费期次
                innerObj.put("accountBank", appDetailProVo.getApplicationFormInvoiceVos().get(0).getOpenBankName());//开户银行
                innerObj.put("bankAccountNo", appDetailProVo.getApplicationFormInvoiceVos().get(0).getOpenBankNumber());//开户银行账号
                t.setParam(innerObj.toString());
                t.setTimes(0);
                issuePolicyLogEntity.setIfCode(ifCode);
                // 电子发票的消费记录入库
                issuePolicyLogEntityMapper.insert(t);

                log.info(DateUtils.getCurrentTime() + "云南诚泰投保单号" + tbNo + "下载发票开始，入参" + innerObj.toString());
                // 调接口  生成发票
                seqNo = Long.toString(Math.abs(new Random().nextLong()));
                responseEntity = dexClient.text("edu", "202011031136360", "1.0", seqNo, innerObj.toString());
                log.info(DateUtils.getCurrentTime() + "云南非九投保单号是 " + tbNo + " 下载发票结束，回参" + responseEntity.getBody());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.error("云南非九请求下载电子发票失败");
                    t.setStatus("6");
                    t.setTimes(1);
                } else {
                    ebody = responseEntity.getBody();
                    String fail = URLDecoder.decode(ebody, "UTF-8");
                    if (fail.contains(ErrorCode.SUCCESS_MSG)) {
                        t.setStatus("2");
                        t.setTimes(1);
                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                    } else {
                        log.error("投保单号:{},电子发票失败原因:{} ", tbNo, fail);
                        t.setStatus("6");
                        t.setTimes(1);
                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                    }
                }
            }
            return true;
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public String getChengtaiPolicy(String policyNo, String partnerCode, String codeKey) {
        String ciphertext = "";
        try {
            ciphertext = SecurityUrl.encrypt(codeKey, policyNo);
            log.info("诚泰保单号{},加密后参数：", ciphertext);
            log.info("原参数{}", policyNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return configurationParameters.getChengtaiPolicy() + partnerCode + "/policyNO/" + ciphertext;
    }

    /**
     * 云南非九（校方综合防范保障保险、教职员工校方责任保险、云南省校方责任保险、校园食品安全责任保险）
     *
     * @param rootElement
     * @return
     */
    private Boolean processYNFJ(Element rootElement, String ifCode) {
        // 解析xml，封装数据
        Element reqPacket = getReqPacket(rootElement);
        Element respPacket = getRespPacket(rootElement);

        String policyType = reqPacket.element("body").element("apply").element("policyType").getStringValue();

        String proCode = IssueEnum.getProCodeByIfCode(ifCode.concat(policyType));

        String companyCode = reqPacket.element("head").element("userId").getStringValue();
        String currentTime = DateUtils.getCurrentTime();
        // 投保单号
        String tbNo = rootElement.element("ApplicationFormCode").getStringValue();
        // 保单号
        String policyNo = rootElement.element("PolicyNo").getStringValue();
        // 入库
        // 入库之前首先判断 是否已经入库  根据投保单号判断
        IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
        issueRecordEntity.setApplicationFormCode(tbNo);
        List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
        if (select != null && select.size() > 0) {
            log.info("系统时间：" + currentTime + ",云南非九投保单号是" + tbNo + "的消息发送重复");
            // 消息重复，消息直接消费完成。
            return true;
        }
        issueRecordEntity.setPolicyNo(policyNo);
        issueRecordEntity.setCompanyCode(companyCode);
        issueRecordEntity.setProCode(proCode);
        issueRecordEntity.setReqPacket(reqPacket.asXML());
        issueRecordEntity.setResPacket(respPacket.asXML());
        issueRecordEntity.setSendStatus("1");
        String status = respPacket.element("Head").element("ResponseCode").getStringValue();
        if ("0".equals(status)) {
            status = "2";
        } else {
            status = "3";
        }
        // 数据中心返回 的投保单状态
        issueRecordEntity.setStatus(status);
        issueRecordEntity.setCreateTime(currentTime);
        issueRecordEntity.setUpdateTime(currentTime);
        issueRecordEntity.setIfCode(ifCode);
        issueRecordEntityMapper.insert(issueRecordEntity);
        if ("3".equals(status)) {
            // 出单失败，消息直接消费完成，在入库的逻辑后边。
            return true;
        }
        // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子保单
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";
        issuePolicyLogEntity.setApplicationFormCode(tbNo);
        issuePolicyLogEntity.setPolicyNo(policyNo);
        issuePolicyLogEntity.setType("1");
        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(proCode);
        String url = respPacket.element("Body").element("Apply").element("PolicyImage").getStringValue();
        // 拼装下载报文
        Document doc = DocumentHelper.createDocument();
        Element info = doc.addElement("Body");
        info.addElement("url").addText(url);
        issuePolicyLogEntity.setParam(info.asXML());
        issuePolicyLogEntity.setIfCode(ifCode);
        issuePolicyLogEntity.setTimes(1);
        issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
        // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
        issueRecordEntity.setSendStatus("2");
        issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);
        //调用接口,请求数据交换中心，下载电子保单
        Boolean flag = false;
        try {
            // 请求下载保单，成功更新
            log.info(DateUtils.getCurrentTime() + "云南非九投保单号是 " + tbNo + " 下载保单开始，入参" + info.asXML());
            String seqNo = Long.toString(Math.abs(new Random().nextLong()));
            ResponseEntity<String> responseEntity = dexClient.text("edu", "20190516016", "1.0", seqNo, info.asXML());
            consumeStatus = "2";
            String ebody = responseEntity.getBody();
            log.info(DateUtils.getCurrentTime() + "云南非九投保单号是 " + tbNo + " 下载保单结束，回参" + ebody);
            doc = DocumentHelper.parseText(ebody);
            Element ebodyElement = doc.getRootElement();
            Element data = ebodyElement.element("data");
            if (data == null) {
                log.error("云南非九请求下载电子保单失败");
                consumeStatus = "3";
            } else {
                String fileId = data.getStringValue();
                issuePolicyLogEntity.setStatus(consumeStatus);
                // 下载成功，更新数据库，绑定资源
                log.info("云南非九 下载消息 fileId ：{}", fileId);
                bindingResources(tbNo, fileId, issuePolicyLogEntity);
                sendEmail(tbNo, "021");
            }
            // todo 下载电子发票 7-15 10:45
            IssuePolicyLogEntity t = new IssuePolicyLogEntity();
            consumeStatus = "1";
            t.setApplicationFormCode(tbNo);
            t.setPolicyNo(policyNo);
            t.setType("3");
            t.setStatus(consumeStatus);
            t.setCreateTime(currentTime);
            t.setUpdateTime(currentTime);
            t.setProCode(proCode);
            doc = DocumentHelper.createDocument();

            // 组装电子发票的报文
            String serialNo = respPacket.element("Head").element("SeqNo").getStringValue();
            String userId = respPacket.element("Head").element("UserId").getStringValue();
            String telephone = reqPacket.element("body").element("apply").element("policyHolder").element("telephone").getStringValue();
            String conEmail = reqPacket.element("body").element("apply").element("policyHolder").element("conEmail").getStringValue();
            String invoiceName = rootElement.element("invoiceName").getStringValue();
            String organizationCode = rootElement.element("organizationCode").getStringValue();
            String invoiceBank = rootElement.element("invoiceBank").getStringValue();
            String invoiceAddress = rootElement.element("invoiceBank").getStringValue();
            info = doc.addElement("FcyBasicLiabilityApply");
            doc.setRootElement(info);
            Element Head = info.addElement("head");
            Head.addElement("userId").addText(userId);
            Head.addElement("commandId").addText("ERA0005");
            Head.addElement("seqNo").addText(serialNo);
            Element Body = info.addElement("body");
            Element apply = Body.addElement("apply");
            apply.addElement("applyId").addText(tbNo);
            apply.addElement("policyNo").addText(policyNo);
            apply.addElement("phoneNumber").addText(telephone);// 电话
            apply.addElement("email").addText(conEmail);// 邮箱
            apply.addElement("organizationCode").addText(organizationCode);
            apply.addElement("invoiceName").addText(invoiceName);
            apply.addElement("invoiceBank").addText(invoiceBank);
            apply.addElement("invoiceAddress").addText(invoiceAddress);
            t.setParam(info.asXML());
            t.setTimes(0);
            issuePolicyLogEntity.setIfCode(ifCode);
            // 电子发票的消费记录入库
            issuePolicyLogEntityMapper.insert(t);

            // 调接口  生成发票
            log.info(DateUtils.getCurrentTime() + "云南非九投保单号是 " + tbNo + " 生成发票开始，入参" + info.asXML());
            seqNo = Long.toString(Math.abs(new Random().nextLong()));
            responseEntity = dexClient.text("edu", "20190516026", "1.0", seqNo, info.asXML());
            consumeStatus = "6";
            ebody = responseEntity.getBody();
            log.info(DateUtils.getCurrentTime() + "云南非九投保单号是 " + tbNo + " 生成发票结束，回参" + ebody);
            doc = DocumentHelper.parseText(ebody);
            ebodyElement = doc.getRootElement();
            // 根据code 0000  判断 。也可以根据返回值data判断  成功有数据，失败为null
            Element body = ebodyElement.element("body");
            Element head = ebodyElement.element("head");
            if (body != null) {// 说明请求成功  返回发票url
                url = body.element("url").getStringValue();
                String msg = head.element("msg").getStringValue();
                if (StringUtil.isEmpty(url)) {
                    log.error("云南非九请求生成电子发票失败");
                    consumeStatus = "7";
                    t.setStatus(consumeStatus);
                    t.setResponseMsg(msg);
                    // 生成电子发票失败，更新数据库，
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    // 组装下载电子发票的报文
                    doc = DocumentHelper.createDocument();
                    info = doc.addElement("Body");
                    Body = info.addElement("url");
                    Body.addText(url);
                    t.setDownParam(info.asXML());
                    t.setStatus(consumeStatus);
                    // 生成电子发票成功，更新数据库，
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                }
            } else {
                log.error("云南非九请求生成电子发票失败");
                consumeStatus = "7";
                t.setStatus(consumeStatus);
                // 生成电子发票失败，更新数据库，
                issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
            }


            // 经过 沟通  等待几秒钟即可 下载发票
            // 调接口  生成发票
            log.info(DateUtils.getCurrentTime() + "云南非九投保单号是 " + tbNo + " 下载发票开始，入参" + info.asXML());
            seqNo = Long.toString(Math.abs(new Random().nextLong()));
            responseEntity = dexClient.text("edu", "20190516036", "1.0", seqNo, info.asXML());

            log.info(DateUtils.getCurrentTime() + "云南非九投保单号是 " + tbNo + " 下载发票结束，回参" + responseEntity.getBody());
            // 请求200，继续执行
            if (responseEntity.getStatusCodeValue() != 200) {
                log.error("云南非九请求下载电子发票失败");
                t.setStatus("6");
                t.setTimes(1);
                issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
            } else {
                ebody = responseEntity.getBody();
                doc = DocumentHelper.parseText(ebody);
                ebodyElement = doc.getRootElement();
                String code = ebodyElement.element("code").getStringValue();
                if ("0000".equals(code)) {
                    String eInvoiceId = ebodyElement.element("data").getStringValue();
                    t.setStatus("2");
                    t.setEInvoiceId(eInvoiceId);
                    bindInvoice(tbNo, eInvoiceId, t);// todo 07-15 11:36
                } else {
                    t.setStatus("6");
                    t.setTimes(1);
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                }
            }
            return true;
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public void sendEmail(String tbNo, String type) {
        //发送云南非九电子保单邮件
        log.info("--send ynEmail begin--" + tbNo);
        AppDetailProVo detailVos = null;
        ResponseEntity<GenericDataResponse<AppDetailProVo>> appDetailPro;
        AppDetailProParam p = new AppDetailProParam();
        p.setAppCode(tbNo);
        p.setChannelCode("edu");    // 渠道编号
        try {
            appDetailPro = insClient.searchAppDetailPro(p);
            detailVos = appDetailPro.getBody().getData();
            MailDTO mailDTO = new MailDTO();
            HolderForProVO holder = detailVos.getHolder();
            String holderCode = holder.getHolderCode();
            User userholder = userService.findEduUserByCode(holderCode);
            mailDTO.setUserName(userholder.getName());
            mailDTO.setProductName(detailVos.getProductName());
            //如果是云南产品,获取到联系人邮箱
            if (IssueEnum.ynProCodeList().contains(detailVos.getProductCode())) {
                mailDTO.setEmail(detailVos.getHolder().getCorporation().getEmail());
            } else {
                mailDTO.setEmail(userholder.getEmail());
            }
            mailDTO.setProposalNo(detailVos.getPolicyNo());
            mailDTO.setOrderNo(detailVos.getOrderCode());
            mailDTO.setPolicyNo(Collections.singletonList(tbNo));

            List<PolAttachmentProVO> attachmentList = detailVos.getPolAttachmentList();
            for (PolAttachmentProVO attachment : attachmentList) {
                if ("A002".equals(attachment.getResCode())) {
                    log.info("Search" + tbNo + "policy success");
                    mailDTO.setPolicyId(attachment.getId());
                }
            }

            if (!StringUtils.isEmpty(userholder.getEmail())) {
                emailsService.sendEmail(mailDTO, type);
            }
        } catch (Exception e) {
            log.error("根据投保单号" + tbNo + "查询投保单信息失败" + e);
        }

        log.info("--send ynEmail end--");

        log.info("--create message start-- productName:{},tbNo:{},policyNo:{},holderCode:{}",
                detailVos.getProductName(), tbNo, detailVos.getPolicyNo(), detailVos.getHolder().getHolderCode());
        createMessage(detailVos.getProductName(), tbNo, detailVos.getPolicyNo(), detailVos.getHolder().getHolderCode());
        log.info("--create message end--");
    }

    private void sendEmailGD(String tbNo, String type) {
        //发送云南非九电子保单邮件
        log.info("--send EmailGD begin--" + tbNo);
        AppDetailProVo detailVos = null;
        ResponseEntity<GenericDataResponse<AppDetailProVo>> appDetailPro;
        AppDetailProParam p = new AppDetailProParam();
        p.setAppCode(tbNo);
        p.setChannelCode("edu");    // 渠道编号
        try {
            appDetailPro = insClient.searchAppDetailPro(p);
            detailVos = appDetailPro.getBody().getData();
            MailDTO mailDTO = new MailDTO();
            HolderForProVO holder = detailVos.getHolder();
            String holderCode = holder.getHolderCode();
            User userholder = userService.findEduUserByCode(holderCode);
            mailDTO.setUserName(userholder.getName());
            mailDTO.setProductName(detailVos.getProductName());
            mailDTO.setEmail(userholder.getEmail());
            mailDTO.setProposalNo(detailVos.getPolicyNo());
            mailDTO.setOrderNo(detailVos.getOrderCode());
            mailDTO.setPolicyNo(Collections.singletonList(tbNo));

            List<PolAttachmentProVO> attachmentList = detailVos.getPolAttachmentList();
            for (PolAttachmentProVO attachment : attachmentList) {
                if ("A002".equals(attachment.getResCode())) {
                    log.info("Search" + tbNo + "policy success  fileUrl" + attachment.getFileUrl());
                    mailDTO.setPolicyId(attachment.getFileUrl());
                }
            }

            if (!StringUtils.isEmpty(userholder.getEmail())) {
                emailsService.sendEmail(mailDTO, type);
            }
        } catch (Exception e) {
            log.error("根据投保单号" + tbNo + "查询投保单信息失败" + e);
        }

        log.info("--send EmailGD end--");

        log.info("--create message start-- productName:{},tbNo:{},policyNo:{},holderCode:{}",
                detailVos.getProductName(), tbNo, detailVos.getPolicyNo(), detailVos.getHolder().getHolderCode());
        createMessage(detailVos.getProductName(), tbNo, detailVos.getPolicyNo(), detailVos.getHolder().getHolderCode());
        log.info("--create message end--");
    }

    private void sendInvoiceEmailGD(String tbNo, String type) {
        //发送云南非九电子保单邮件
        log.info("--send InvoiceEmailGD begin--" + tbNo);
        AppDetailProVo detailVos = null;
        ResponseEntity<GenericDataResponse<AppDetailProVo>> appDetailPro;
        AppDetailProParam p = new AppDetailProParam();
        p.setAppCode(tbNo);
        p.setChannelCode("edu");    // 渠道编号
        try {
            appDetailPro = insClient.searchAppDetailPro(p);
            detailVos = appDetailPro.getBody().getData();
            MailDTO mailDTO = new MailDTO();
            HolderForProVO holder = detailVos.getHolder();
            String holderCode = holder.getHolderCode();
            User userholder = userService.findEduUserByCode(holderCode);
            mailDTO.setUserName(userholder.getName());
            mailDTO.setProductName(detailVos.getProductName());
            mailDTO.setEmail(userholder.getEmail());
            mailDTO.setProposalNo(detailVos.getPolicyNo());
            mailDTO.setOrderNo(detailVos.getOrderCode());
            mailDTO.setPolicyNo(Collections.singletonList(tbNo));

            List<AttachmentForProVO> appAttachmentList = detailVos.getAppAttachmentList();
            for (AttachmentForProVO attachment : appAttachmentList) {
                if ("P001".equals(attachment.getResCode())) {
                    log.info("Search" + tbNo + "invoice success  fileUrl" + attachment.getFileUrl());
                    mailDTO.setPolicyId(attachment.getFileUrl());
                }
            }

            if (!StringUtils.isEmpty(userholder.getEmail())) {
                emailsService.sendEmail(mailDTO, type);
            }
        } catch (Exception e) {
            log.error("根据投保单号" + tbNo + "查询投保单信息失败" + e);
        }

        log.info("--send InvoiceEmailGD end--");

        /*log.info("--create message start-- productName:{},tbNo:{},policyNo:{},holderCode:{}",
                detailVos.getProductName(), tbNo, detailVos.getPolicyNo(), detailVos.getHolder().getHolderCode());
        createMessage(detailVos.getProductName(), tbNo, detailVos.getPolicyNo(), detailVos.getHolder().getHolderCode());
        log.info("--create message end--");*/
    }

    /**
     * 出单成功 生成消息
     *
     * @param productName
     * @param tbNo
     * @param policyNo
     * @param holderCode
     */
    private void createMessage(String productName, String tbNo, String policyNo, String holderCode) {

        try {

            log.info("出单成功 生成消息 productName:{},tbNo:{},policyNo:{},holderCode:{}", productName, tbNo, policyNo, holderCode);

            MessageInfoEntity entity = new MessageInfoEntity();
            entity.setNoticeState(false);
            entity.setCreateTime(DateUtils.getCurrentTime());
            entity.setMessageTitle("出单成功");
            entity.setMessageContent("您投保的" + productName + "产品（投保单号：" + tbNo + "）已出单成功，保单号为：" + policyNo + ",按照" + productName + "项目（产品）的约定，保险合同成立并生效。");
            entity.setIsDeleted(false);
            entity.setTargetUser(holderCode);
            entity.setMessageType(MESSAGE_TYPE);
            entity.setNoticeType(0);
            entity.setRecordType(1);
            entity.setMessageUrl("/userCenter/insurdetails?data=" + tbNo);
            int num = messageService.addMessageInfo(entity);

            if (num > 0) {
                log.info("生成出单成功消息成功：投保单号{},保单号{},消息内容{}", tbNo, policyNo, entity.getMessageContent());
            } else {
                log.info("生成出单成功消息失败：投保单号{},保单号{}", tbNo, policyNo);
            }
        } catch (Exception e) {
            log.error("生成出单成功消息异常 投保单号{}：，异常信息{}", tbNo, e);
        }
    }

    /**
     * 获取电子发票类型,以及发票信息
     *
     * @param appCode
     * @return
     */
    public Map<String, String> getAppcodeInvoiceType(String appCode) {
        Map<String, String> invoices = Maps.newHashMap();
        String invoiceType = InvoiceTypeEnum.PAPER_EXCLUSIVE.getType();
        String bankAddress = ""; //购方开户地址  选填
        String mobile = ""; //购方联系电话  选填
        String bankName = ""; // 购方开户行名称  选填
        String bankNo = ""; //购方银行账户  选填
        String taxpayerIdentificationNumber = ""; //纳税人识别号
        String title = "";
        AppDetailProVo appDetailProVo = insAppDetailList(appCode);
        List<ApplicationFormInvoiceVo> invoiceVoList = appDetailProVo.getApplicationFormInvoiceVos();
        if (invoiceVoList.size() != 0) {
            for (ApplicationFormInvoiceVo invoiceVoListVo : invoiceVoList) {
                invoiceType = invoiceVoListVo.getInvoiceType();
                bankAddress = invoiceVoListVo.getTaxpayerAddress();
                mobile = invoiceVoListVo.getTaxpayerTelephone();
                bankName = invoiceVoListVo.getOpenBankName();
                bankNo = invoiceVoListVo.getOpenBankNumber();
                taxpayerIdentificationNumber = invoiceVoListVo.getTaxpayerIdentificationNumber();
                title = invoiceVoListVo.getTitle();
            }
        }
        invoices.put("invoiceType", invoiceType);
        invoices.put("bankAddress", bankAddress);
        invoices.put("mobile", mobile);
        invoices.put("bankName", bankName);
        invoices.put("bankNo", bankNo);
        invoices.put("taxpayerIdentificationNumber", taxpayerIdentificationNumber);
        invoices.put("title", title);
        return invoices;
    }

    public AppDetailProVo insAppDetailList(String appCode) {
        log.info("query insClient application 开始--" + appCode);
        AppDetailProVo detailVos = null;
        ResponseEntity<GenericDataResponse<AppDetailProVo>> appDetailPro;
        AppDetailProParam p = new AppDetailProParam();
        p.setAppCode(appCode);
        p.setChannelCode("edu");    // 渠道编号
        try {
            appDetailPro = insClient.searchAppDetailPro(p);
            detailVos = appDetailPro.getBody().getData();
        } catch (Exception e) {
            log.error("调用ins服务失败,错误信息:{} 投保单号为:{} ", e, appCode);
            e.printStackTrace();
        }
        return detailVos;
    }

    /**
     * 判断金额是否小于10w，10w之内才能开具电子发票
     *
     * @param fee
     * @return
     */
    public Boolean judgingTheAmount(String fee) {
        return new BigDecimal(fee).compareTo(new BigDecimal("100000")) == -1;
    }

    /**
     * 1实责（全国职业院校学生实习责任保险）  2校责（校方责任保险）
     *
     * @param rootElement
     * @return
     */
    private Boolean processSZAndXZ(Element rootElement, String ifCode) {
        Element reqPacket = getReqPacket(rootElement);
        Element respPacket = getRespPacket(rootElement);
        String companyCode = reqPacket.element("Head").element("UserId").getStringValue();
        String proCode = null;
        String mainTypeStr = "";
        String currentTime = DateUtils.getCurrentTime();
        Iterator iterator = respPacket.element("Body").elementIterator("Apply");
        // 只有山西地区  有发票
        Iterator iteratorReq = reqPacket.element("Body").elementIterator("Apply");
        String desc = PolicyEnum.getIssueEnum(ifCode).getDesc();
        // 投保单号和出单地区 组装的map
        Map<String, String> map = new HashMap();
        Map<String, String> taxMap = new HashMap();
        Map<String, String> mainTypeMap = new HashMap();
        Map<String, String> proCodeMap = new HashMap();
        while (iteratorReq.hasNext()) {
            Element nextReq = (Element) iteratorReq.next();
            String tbNo = nextReq.element("ApplyId").getStringValue();
            String issuingCompanyId = nextReq.element("IssuingCompanyId").getStringValue();
            String OrganizationCode = nextReq.element("PolicyHolder").element("OrganizationCode").getStringValue();
            String mainType = nextReq.element("MainType").getStringValue();
            proCode = IssueEnum.getProCodeByIfCode(ifCode.concat(mainType));
            mainTypeMap.put(tbNo, mainType);
            proCodeMap.put(tbNo, proCode);
            taxMap.put(tbNo, OrganizationCode);
            map.put(tbNo, issuingCompanyId);
        }
        int size = map.size();// 请求体的集合和响应体的集合 size相等
        int i = 0;
        while (iterator.hasNext()) {
            Element nextResp = (Element) iterator.next();
            // 投保单号
            String tbNo = nextResp.element("ApplyId").getStringValue();
            // 保单号
            String policyNo = nextResp.element("PolicyNo").getStringValue();
            String fee = nextResp.element("Fee").getStringValue();
            proCode = proCodeMap.get(tbNo);
            mainTypeStr = mainTypeMap.get(tbNo);

            // 入库
            // 入库之前首先判断 是否已经入库  根据投保单号判断
            IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
            issueRecordEntity.setApplicationFormCode(tbNo);
            List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
            if (select == null || select.size() == 0) {
                issueRecordEntity.setPolicyNo(policyNo);
                issueRecordEntity.setCompanyCode(companyCode);
                issueRecordEntity.setProCode(proCode);
                issueRecordEntity.setReqPacket(reqPacket.asXML());
                issueRecordEntity.setResPacket(respPacket.asXML());
                issueRecordEntity.setSendStatus("1");
                issueRecordEntity.setMainType(mainTypeStr);
                String status = respPacket.element("Head").element("ResponseCode").getStringValue();

                if ("0".equals(status)) {
                    status = "2";
                } else {
                    status = "3";
                }
                // 数据中心返回 的投保单状态
                issueRecordEntity.setStatus(status);
                issueRecordEntity.setCreateTime(currentTime);
                issueRecordEntity.setUpdateTime(currentTime);
                issueRecordEntity.setIfCode(ifCode);
                issueRecordEntityMapper.insert(issueRecordEntity);

                if ("2".equals(status)) { // 成功
                    // 消费  ： 需要组织报文，去调用接口
                    IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
                    String consumeStatus = "1";
                    issuePolicyLogEntity.setApplicationFormCode(tbNo);
                    issuePolicyLogEntity.setPolicyNo(policyNo);
                    issuePolicyLogEntity.setType("1");
                    issuePolicyLogEntity.setStatus(consumeStatus);
                    issuePolicyLogEntity.setCreateTime(currentTime);
                    issuePolicyLogEntity.setUpdateTime(currentTime);
                    issuePolicyLogEntity.setProCode(proCode);
                    // 组装报文
                    Document doc = DocumentHelper.createDocument();
                    Element info = doc.addElement("POLICYNO");
                    info.addText(policyNo);
                    issuePolicyLogEntity.setParam(info.asXML());
                    issuePolicyLogEntity.setMainType(mainTypeStr);
                    issuePolicyLogEntity.setTimes(0);
                    issuePolicyLogEntity.setIfCode(ifCode);
                    issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
                    // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
                    issueRecordEntity.setSendStatus("2");
                    issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);

                    try {
                        // 请求下载保单，成功更新
                        log.info(DateUtils.getCurrentTime() + desc + "保单号是" + tbNo + "下载保单开始，入参" + info.asXML());
                        String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                        //根据ifCode判断是否调用哪个接口
                        String policy = PolicyEnum.getPolicyOrInvoiceByIfCode(ifCode, "POLICY");
                        String invoice = PolicyEnum.getPolicyOrInvoiceByIfCode(ifCode, "INVOICE");
                        String ebody = null;
                        ResponseEntity<String> responseEntity = dexClient.text("edu", policy, "1.0", seqNo, info.asXML());
                        if (responseEntity != null) {
                            ebody = responseEntity.getBody();

                            log.info(DateUtils.getCurrentTime() + "实责校责保单号是" + tbNo + "下载保单结束，回参" + responseEntity.getStatusCodeValue() + "," + ebody);
                            try {
                                doc = DocumentHelper.parseText(ebody);
                                Element ebodyElement = doc.getRootElement();
                                Element data = ebodyElement.element("data");
                                String fileId = "";
                                if (data == null) {
                                    log.error(desc + "请求下载电子保单失败");
                                    consumeStatus = "3";
                                } else {
                                    consumeStatus = "2";
                                    fileId = data.getStringValue();
                                }
                                issuePolicyLogEntity.setStatus(consumeStatus);
                                // 下载电子保单成功，更新数据库，绑定资源
                                log.info(desc + "下载消息 fileId ：{}", fileId);
                                bindingResources(tbNo, fileId, issuePolicyLogEntity);
                            } catch (Exception e) {
                                log.error(desc + "请求下载电子保单异常", e);
                            }
                        }

                        Map<String, String> invoiceList = getAppcodeInvoiceType(tbNo);
                        // 只有山西地区  有发票
                        String issuingCompanyId = map.get(tbNo);
                        //阳光统保地区山西，金额小于10w默认开具电子发票，别的地区选择电子发票就去开，纸质发票不去开具，金额大于10w元的也不去开具
                        if (("301400".equals(issuingCompanyId) && judgingTheAmount(fee)) || (invoiceList.get("invoiceType").equals(InvoiceTypeEnum.ELECTRONIC_INVOICE.getType()) && judgingTheAmount(fee))) { // 有发票
                            //todo 7-13 11:58
                            // 下载电子发票 拼装参数
                            IssuePolicyLogEntity t = new IssuePolicyLogEntity();
                            consumeStatus = "6";
                            t.setApplicationFormCode(tbNo);
                            t.setPolicyNo(policyNo);
                            t.setType("3");
                            t.setStatus(consumeStatus);
                            t.setCreateTime(currentTime);
                            t.setUpdateTime(currentTime);
                            t.setProCode(proCode);
                            t.setMainType(mainTypeStr);
                            t.setIfCode(ifCode);
                            doc = DocumentHelper.createDocument();
                            // 组装电子发票的报文
                            String serialNo = respPacket.element("Head").element("SeqNo").getStringValue();
                            String taxpayerNo = taxMap.get(tbNo);
                            info = doc.addElement("INSURENCEINFO");
                            doc.setRootElement(info);

                            Element policylist = info.addElement("POLICYLIST");
                            Element ismerge = policylist.addElement("ISMERGE");
                            ismerge.addText("0");
                            Element POLICYINFO = policylist.addElement("POLICYINFO");
                            Element productcode = POLICYINFO.addElement("PRODUCTCODE");
                            if ("1".equals(mainTypeStr)) {// 实责
                                productcode.addText("151901");
                            } else if ("2".equals(mainTypeStr)) {// 校责
                                productcode.addText("151301");
                            }
                            POLICYINFO.addElement("SERIALNO").addText(serialNo);
                            POLICYINFO.addElement("POLICYNO").addText(policyNo);
                            POLICYINFO.addElement("INVOICETYPE").addText("2");
                            POLICYINFO.addElement("TAXPAYERNO").addText(taxpayerNo);
                            //新增购方信息
                            String bankAddress = invoiceList.get("bankAddress");
                            String mobile = invoiceList.get("mobile");
                            String bankName = invoiceList.get("bankName");
                            String bankNo = invoiceList.get("bankNo");
                            POLICYINFO.addElement("BANKADDRESS").addText(StringUtils.isEmpty(bankAddress) ? "" : bankAddress);
                            POLICYINFO.addElement("MOBILE").addText(StringUtils.isEmpty(mobile) ? "" : mobile);
                            POLICYINFO.addElement("BANKNAME").addText(StringUtils.isEmpty(bankName) ? "" : bankName);
                            POLICYINFO.addElement("BANKNO").addText(StringUtils.isEmpty(bankNo) ? "" : bankNo);
                            Element AMOUNT = policylist.addElement("AMOUNT");
                            AMOUNT.addText("1");
                            Element TOTALJYJE = policylist.addElement("TOTALJYJE");
                            TOTALJYJE.addText(fee);
                            t.setParam(info.asXML());
                            t.setTimes(1);
                            issuePolicyLogEntity.setIfCode(ifCode);
                            // 电子发票的消费记录入库
                            issuePolicyLogEntityMapper.insert(t);
                            // 刘高逻辑：直接去下载即可。
                            log.info(DateUtils.getCurrentTime() + desc + "投保单号是" + tbNo + "下载发票开始，入参" + info.asXML());
                            seqNo = Long.toString(Math.abs(new Random().nextLong()));
                            responseEntity = dexClient.text("edu", invoice, "1.0", seqNo, info.asXML());
                            log.info(DateUtils.getCurrentTime() + desc + "投保单号是" + tbNo + "下载发票结束，回参" + responseEntity.getStatusCodeValue() + "," + responseEntity.getBody());
                            if (responseEntity != null) {
                                // 请求200，继续执行
                                if (responseEntity.getStatusCodeValue() != 200) {
                                    log.error(desc + "请求下载电子保单失败");
                                    t.setStatus("6");
                                    t.setTimes(1);
                                    t.setUpdateTime(currentTime);
                                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                                } else {
                                    ebody = responseEntity.getBody();
                                    doc = DocumentHelper.parseText(ebody);
                                    Element ebodyElement = doc.getRootElement();
                                    String code = ebodyElement.element("code").getStringValue();
                                    if ("0000".equals(code)) {
                                        String eInvoiceId = ebodyElement.element("data").getStringValue();
                                        t.setStatus("2");
                                        t.setUpdateTime(currentTime);
                                        t.setEInvoiceId(eInvoiceId);
                                        bindInvoice(tbNo, eInvoiceId, t);// todo 07-09 15:12
                                    } else {
                                        t.setStatus("6");
                                        t.setTimes(1);
                                        t.setUpdateTime(currentTime);
                                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                                    }
                                }
                            }
                            i++;
                        } else {// 没有发票
                            i++;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        issuePolicyLogEntity.setTimes(1);
                        issuePolicyLogEntity.setStatus("3");
                        issuePolicyLogEntity.setUpdateTime(currentTime);
                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(issuePolicyLogEntity);
                    }
                } else {
                    status = "3";
                    i++;
                }
            } else {
                log.info("系统时间：" + currentTime + desc + ",投保单号是" + tbNo + "的消息发送重复");
                i++;
            }
            sendEmail(tbNo, "21");
        }
        return true;
    }

    /**
     * 学责险（学生安全责任保险）
     *
     * @param rootElement
     * @return
     */
    private Boolean processXZ(Element rootElement, String ifCode) {
        // 解析xml，封装数据
        Element reqPacket = getReqPacket(rootElement);
        Element respPacket = getRespPacket(rootElement);

        String mainTypeStr = "0";
        //String proCode = reqPacket.element("Body").element("Apply").element("PolicyHolder").element("PolicyType").getStringValue();
        String proCode = IssueEnum.getProCodeByIfCode(ifCode);
        String companyCode = reqPacket.element("Head").element("UserId").getStringValue();
        String currentTime = DateUtils.getCurrentTime();
        // 投保单号
        String tbNo = rootElement.element("ApplicationFormCode").getStringValue();
        // 保单号
        String policyNo = rootElement.element("PolicyNo").getStringValue();
        // 入库
        // 入库之前首先判断 是否已经入库  根据投保单号判断
        IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
        issueRecordEntity.setApplicationFormCode(tbNo);
        List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
        if (select != null && select.size() > 0) {
            log.info("系统时间：" + currentTime + ",学责投保单号是" + tbNo + "的消息发送重复");
            // 消息重复，消息直接消费完成。
            return true;
        }

        issueRecordEntity.setMainType(mainTypeStr);
        issueRecordEntity.setPolicyNo(policyNo);
        issueRecordEntity.setCompanyCode(companyCode);
        issueRecordEntity.setProCode(proCode);
        issueRecordEntity.setReqPacket(reqPacket.asXML());
        issueRecordEntity.setResPacket(respPacket.asXML());
        issueRecordEntity.setSendStatus("1");
        String status = respPacket.element("Head").element("ResponseCode").getStringValue();
        if ("0".equals(status)) {// 成功
            status = "2";
        } else {
            status = "3";
        }
        // 数据中心返回 的投保单状态
        issueRecordEntity.setStatus(status);

        issueRecordEntity.setCreateTime(currentTime);
        issueRecordEntity.setUpdateTime(currentTime);
        issueRecordEntity.setIfCode(ifCode);
        issueRecordEntityMapper.insert(issueRecordEntity);
        if ("3".equals(status)) {// 成功
            // 出单失败，消息直接消费完成。
            return true;
        }
        // 消费  ： 需要组织报文，去调用接口
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";
        issuePolicyLogEntity.setApplicationFormCode(tbNo);
        issuePolicyLogEntity.setPolicyNo(policyNo);
        issuePolicyLogEntity.setType("1");
        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(proCode);
        // 组装报文
        Document doc = DocumentHelper.createDocument();
        Element info = doc.addElement("Message");
        doc.setRootElement(info);
        Element body = info.addElement("Body");
        Element policies = body.addElement("Policies");
        policies.addElement("ApplicationFormCode").addText(tbNo);
        policies.addElement("PolicyNo").addText(policyNo);
        policies.addElement("CompanyCode").addText(companyCode);
        issuePolicyLogEntity.setParam(info.asXML());
        issuePolicyLogEntity.setMainType(mainTypeStr);
        issuePolicyLogEntity.setTimes(0);
        issuePolicyLogEntity.setIfCode(ifCode);
        issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
        // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
        issueRecordEntity.setSendStatus("2");
        issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);

        Boolean flag = false;
        try {
            // 请求下载保单，成功更新
            log.info(DateUtils.getCurrentTime() + "学责投保单号" + tbNo + "下载保单开始，入参" + info.asXML());
            String seqNo = Long.toString(Math.abs(new Random().nextLong()));
            ResponseEntity<String> responseEntity = null;
            try {
                responseEntity = dexClient.text("edu", "20190515003", "1.0", seqNo, info.asXML());
                String ebody = responseEntity.getBody();
                log.info(DateUtils.getCurrentTime() + "学责投保单号" + tbNo + "下载保单结束，回参" + ebody + "," + responseEntity.getStatusCodeValue());
                doc = DocumentHelper.parseText(ebody);
                Element ebodyElement = doc.getRootElement();
                Element data = ebodyElement.element("data");
                consumeStatus = "2";
                if (data == null) {
                    log.error("学责请求下载电子保单失败");
                    consumeStatus = "3";
                }
                String fileId = data.getStringValue();
                issuePolicyLogEntity.setStatus(consumeStatus);
                // 下载电子保单成功，更新数据库，绑定资源
                log.info("学责 下载消息 fileId ：{}", fileId);
                bindingResources(tbNo, fileId, issuePolicyLogEntity);
            } catch (Exception e) {
                e.printStackTrace();
                issuePolicyLogEntity.setTimes(1);
                issuePolicyLogEntity.setStatus("3");
                issuePolicyLogEntityMapper.updateByPrimaryKeySelective(issuePolicyLogEntity);

            }
            sendEmail(tbNo, "21");
            Map<String, String> invoiceList = getAppcodeInvoiceType(tbNo);
            // 只有山西地区  有发票
            String issuingCompanyId = reqPacket.element("Body").element("Apply").element("IssuingCompanyInfo").element("IssuingCompanyId").getStringValue();
            /*if ("301400".equals(issuingCompanyId)) {*/ // 有发票
            if (invoiceList.get("invoiceType").equals(InvoiceTypeEnum.ELECTRONIC_INVOICE.getType())) {

                log.info(DateUtils.getCurrentTime() + "学责山西地区生成发票开始，，，");
                // 下载电子发票 拼装参数
                IssuePolicyLogEntity t = new IssuePolicyLogEntity();
                consumeStatus = "1";
                t.setApplicationFormCode(tbNo);
                t.setPolicyNo(policyNo);
                t.setType("3");
                t.setStatus(consumeStatus);
                t.setCreateTime(currentTime);
                t.setUpdateTime(currentTime);
                t.setProCode(proCode);
                t.setMainType(mainTypeStr);
                t.setIfCode(ifCode);
                doc = DocumentHelper.createDocument();

                // 组装电子发票的报文
                String serialNo = respPacket.element("Head").element("SeqNo").getStringValue();
                String fee = respPacket.element("Body").element("Apply").element("Fee").getStringValue();
                String taxpayerNo = reqPacket.element("Body").element("Apply").element("PolicyHolder").element("IdenCode").getStringValue();
                info = doc.addElement("Message");
                doc.setRootElement(info);
                Element Head = info.addElement("Head");
                Head.addElement("OrderNo").addText("");
                Element Body = info.addElement("Body");
                Element policyInfo = Body.addElement("PolicyInfo");
                policyInfo.addElement("PRODUCTCODE").addText("152901");
                policyInfo.addElement("SerialNo").addText(serialNo);
                policyInfo.addElement("PolicyNo").addText(policyNo);
                policyInfo.addElement("TaxpayerNo").addText(taxpayerNo);
                //新增购方信息
                String bankAddress = invoiceList.get("bankAddress");
                String mobile = invoiceList.get("mobile");
                String bankName = invoiceList.get("bankName");
                String bankNo = invoiceList.get("bankNo");
                policyInfo.addElement("BANKADDRESS").addText(StringUtils.isEmpty(bankAddress) ? "" : bankAddress);
                policyInfo.addElement("MOBILE").addText(StringUtils.isEmpty(mobile) ? "" : mobile);
                policyInfo.addElement("BANKNAME").addText(StringUtils.isEmpty(bankName) ? "" : bankName);
                policyInfo.addElement("BANKNO").addText(StringUtils.isEmpty(bankNo) ? "" : bankNo);
                policyInfo.addElement("Amount").addText("1");
                policyInfo.addElement("TotalJyje").addText(fee);
                t.setParam(info.asXML());
                t.setTimes(0);
                issuePolicyLogEntity.setIfCode(ifCode);
                // 电子发票的消费记录入库
                issuePolicyLogEntityMapper.insert(t);

                log.info(DateUtils.getCurrentTime() + "学责投保单号" + tbNo + "生成发票开始，入参" + info.asXML());
                // 调接口  生成发票
                seqNo = Long.toString(Math.abs(new Random().nextLong()));
                responseEntity = dexClient.text("edu", "20190515013", "1.0", seqNo, info.asXML());
                consumeStatus = "6";
                String ebody = responseEntity.getBody();
                log.info(DateUtils.getCurrentTime() + "学责投保单号" + tbNo + "生成发票结束，回参" + ebody + "," + responseEntity.getStatusCodeValue());
                doc = DocumentHelper.parseText(ebody);
                Element ebodyElement = doc.getRootElement();
                String code = ebodyElement.element("POLICY").attributeValue("RETURN");

                Element downData = null;
                if ("true".equals(code)) {
                    doc = DocumentHelper.createDocument();
                    info = doc.addElement("Message");
                    doc.setRootElement(info);
                    Body = info.addElement("Body");
                    t.setDownParam(info.asXML());
                    t.setStatus(consumeStatus);
                    // 生成电子发票成功，更新数据库，
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    log.error("请求生成电子保单失败");
                    consumeStatus = "7";
                    t.setStatus(consumeStatus);
                    // 生成电子发票失败，更新数据库，
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                    return true;
                }

                log.info(DateUtils.getCurrentTime() + "学责投保单号" + tbNo + "下载发票开始，入参" + info.asXML());
                seqNo = Long.toString(Math.abs(new Random().nextLong()));
                responseEntity = dexClient.text("edu", "20190515013", "1.1", seqNo, info.asXML());
                log.info(DateUtils.getCurrentTime() + "学责投保单号" + tbNo + "下载发票结束，回参" + responseEntity.getBody() + "," + responseEntity.getStatusCodeValue());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.error("请求下载电子发票失败");
                    t.setStatus("6");
                    t.setTimes(1);
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    ebody = responseEntity.getBody();
                    doc = DocumentHelper.parseText(ebody);
                    ebodyElement = doc.getRootElement();
                    code = ebodyElement.element("code").getStringValue();
                    if ("0000".equals(code)) {
                        String eInvoiceId = ebodyElement.element("data").getStringValue();
                        t.setStatus("2");
                        t.setEInvoiceId(eInvoiceId);
                        bindInvoice(tbNo, eInvoiceId, t);// todo 07-09 15:12
                    } else {
                        t.setStatus("6");
                        t.setTimes(1);
                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                    }
                }
            }
            log.info(DateUtils.getCurrentTime() + "学责山西地区生成发票结束，，，");
            /*}else {// 没有发票
                log.info(DateUtils.getCurrentTime() + "学责非山西地区不用生成发票，，，");
            }*/
            return true;
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 山东产品（山东省校（园）方责任保险项目）
     *
     * @param rootElement
     * @return
     */
    private Boolean processSD(Element rootElement, String ifCode) {
        // 解析xml，封装数据
        Element reqPacket = getReqPacket(rootElement);
        Element respPacket = getRespPacket(rootElement);

        String proCode = IssueEnum.getProCodeByIfCode(ifCode);

        Element body = reqPacket.element("body");
        String companyCode = reqPacket.element("head").element("userId").getStringValue();
        String currentTime = DateUtils.getCurrentTime();
        // 投保单号
        String tbNo = rootElement.element("ApplicationFormCode").getStringValue();
        // 保单号
        String policyNo = rootElement.element("PolicyNo").getStringValue();
        // 入库
        // 入库之前首先判断 是否已经入库  根据投保单号判断
        IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
        issueRecordEntity.setApplicationFormCode(tbNo);
        List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
        if (select != null && select.size() > 0) {
            log.info("系统时间：{}, 山东校责投保单号是 {} 的消息发送重复", currentTime, tbNo);
            // 消息重复，消息直接消费完成。
            return true;
        }
        issueRecordEntity.setPolicyNo(policyNo);
        issueRecordEntity.setCompanyCode(companyCode);
        issueRecordEntity.setProCode(proCode);
        issueRecordEntity.setReqPacket(reqPacket.asXML());
        issueRecordEntity.setResPacket(respPacket.asXML());
        issueRecordEntity.setSendStatus("1");
        String status = respPacket.element("head").element("responseCode").getStringValue();
        if ("9200".equals(status)) {
            status = "2";
        } else {
            status = "3";
        }
        // 数据中心返回 的投保单状态
        issueRecordEntity.setStatus(status);
        issueRecordEntity.setCreateTime(currentTime);
        issueRecordEntity.setUpdateTime(currentTime);
        issueRecordEntity.setIfCode(ifCode);
        issueRecordEntityMapper.insert(issueRecordEntity);
        if ("3".equals(status)) {
            // 出单失败，消息直接消费完成，在入库的逻辑后边。
            return true;
        }
        // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子保单
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";
        issuePolicyLogEntity.setApplicationFormCode(tbNo);
        issuePolicyLogEntity.setPolicyNo(policyNo);
        issuePolicyLogEntity.setType("1");
        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(proCode);
        String url = respPacket.element("body").element("apply").element("electricalDocument").getStringValue();
        // 拼装下载报文
        Document doc = DocumentHelper.createDocument();
        Element info = doc.addElement("body");
        info.addElement("url").addText(url);
        issuePolicyLogEntity.setParam(info.asXML());
        issuePolicyLogEntity.setTimes(0);
        issuePolicyLogEntity.setIfCode(ifCode);
        issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
        // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
        issueRecordEntity.setSendStatus("2");
        issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);
        //调用接口,请求数据交换中心，下载电子保单
        try {
            log.info("山东校责的投保单号是 {}, 保单下载参数：{}", tbNo, info.asXML());
            // 请求下载保单，成功更新
            String seqNo = Long.toString(Math.abs(new Random().nextLong()));
            ResponseEntity<String> responseEntity = dexClient.text("edu", "20190516022", "1.0", seqNo, info.asXML());
            log.info("山东校责的投保单号是 {}, 保单下载返回值：{}, {}", tbNo, responseEntity.getStatusCodeValue(), responseEntity.getBody());
            consumeStatus = "2";
            String fileId = responseEntity.getBody();
            issuePolicyLogEntity.setStatus(consumeStatus);
            // 下载成功，更新数据库，绑定资源
            log.info("山东校责 下载消息 fileId ：{}", fileId);
            bindingResources(tbNo, fileId, issuePolicyLogEntity);
            return true;
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        sendEmail(tbNo, "21");
        return false;
    }

    /**
     * 阳光财产安责保护伞
     *
     * @param rootElement
     * @return
     */
    private Boolean processAZBHS(Element rootElement, String ifCode) {
        Element respPacket = getRespPacket(rootElement);
        Element reqPacket = getReqPacket(rootElement);

        String currentTime = DateUtils.getCurrentTime();
        // 投保单号
        String tbNo = rootElement.element("ApplicationFormCode").getStringValue();
        // 保单号
        String policyNo = rootElement.element("PolicyNo").getStringValue();
        // 解析险种
        //String proCode = reqPacket.element("Body").element("Apply").element("PolicyInfo").element("PolicyType").getStringValue();
        String proCode = IssueEnum.getProCodeByIfCode(ifCode);

        log.debug("系统时间：{}, [阳光财产安责保护伞]下载电子保单 投保单号：{},保单号：{},产品险种编码：{}", currentTime, tbNo, policyNo, proCode);
        // 入库
        // 入库之前首先判断 是否已经入库  根据投保单号判断
        IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
        issueRecordEntity.setApplicationFormCode(tbNo);
        List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
        if (select != null && select.size() > 0) {
            log.info("系统时间：{}, 阳光财产安责保护伞投保单号是：{} 的消息发送重复", currentTime, tbNo);
            // 消息重复，消息直接消费完成。
            return true;
        }
        issueRecordEntity.setPolicyNo(policyNo);
        issueRecordEntity.setProCode(proCode);
        issueRecordEntity.setReqPacket(reqPacket.asXML());
        issueRecordEntity.setResPacket(respPacket.asXML());
        issueRecordEntity.setSendStatus("1");
        String status = null;
        //0：成功  其余：失败
        //如果是关爱宝获取状态标示
        if (ifCode.equals("20200211001") || ifCode.equals("20200330006") || ifCode.equals("202006171149460")) {
            status = respPacket.element("ORDER").attributeValue("RETURN");
            if ("true".equals(status)) {
                status = "2";
            } else {
                status = "3";
            }
        } else if (ifCode.equals("202008191339340")) {
            status = respPacket.element("respCode").getStringValue();
            if ("0000".equals(status)) {
                status = "2";
            } else {
                status = "3";
            }
        } else {
            status = respPacket.element("Head").element("ResponseCode").getStringValue();
            if ("0".equals(status)) {
                status = "2";
            } else {
                status = "3";
            }
        }


        // 数据中心返回 的投保单状态
        issueRecordEntity.setStatus(status);
        issueRecordEntity.setCreateTime(currentTime);
        issueRecordEntity.setUpdateTime(currentTime);
        issueRecordEntity.setIfCode(ifCode);
        issueRecordEntityMapper.insert(issueRecordEntity);
        if ("3".equals(status)) {
            // 出单失败或者重复出单，消息直接消费完成，在入库的逻辑后边。
            return true;
        }
        // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子保单
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";
        issuePolicyLogEntity.setApplicationFormCode(tbNo);
        issuePolicyLogEntity.setPolicyNo(policyNo);
        issuePolicyLogEntity.setType("1");
        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(proCode);
        // 拼装下载报文
        Document doc = DocumentHelper.createDocument();
        Element info = doc.addElement("data");
        info.addElement("policyNo").addText(policyNo);
        issuePolicyLogEntity.setParam(info.asXML());
        issuePolicyLogEntity.setTimes(0);
        issuePolicyLogEntity.setIfCode(ifCode);
        issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
        // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
        issueRecordEntity.setSendStatus("2");
        issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);

        //调用接口,请求数据交换中心，下载电子保单
        try {
            log.info("阳光财产安责保护伞的投保单号是: {}, 保单下载参数：{}", tbNo, info.asXML());
            // 请求下载保单，成功更新
            String seqNo = Long.toString(Math.abs(new Random().nextLong()));
            ResponseEntity<String> responseEntity = null;
            if (ifCode.equals("20200211001")) {
                responseEntity = dexClient.text("edu", "20200212012", "1.0", seqNo, info.asXML());

            } else if (ifCode.equals("20200330006")) {
                responseEntity = dexClient.text("edu", "20200330012", "1.0", seqNo, info.asXML());
            } else if (ifCode.equals("202006171149460")) {
                responseEntity = dexClient.text("edu", "202006171156520", "1.0", seqNo, info.asXML());
            } else if (ifCode.equals("20200807001")) {
                responseEntity = dexClient.text("edu", "20200817012", "1.0", seqNo, info.asXML());
            } else if (ifCode.equals("202008191339340")) {
                responseEntity = dexClient.text("edu", "202008191353580", "1.0", seqNo, info.asXML());
            } else {
                responseEntity = dexClient.text("edu", "20190515016", "1.0", seqNo, info.asXML());

            }

            String ebody = responseEntity.getBody();
            log.info("阳光财产安责保护伞的投保单号是: {}, 保单下载返回值：{}, {}", tbNo, responseEntity.getStatusCodeValue(), responseEntity.getBody());

            Document resultDoc = DocumentHelper.createDocument();
            resultDoc = DocumentHelper.parseText(ebody);
            Element ebodyElement = resultDoc.getRootElement();
            Element data = ebodyElement.element("data");
            consumeStatus = "2";
            if (data == null) {
                log.error("阳光财产安责保护伞请求下载电子保单失败");
                consumeStatus = "3";
            }
            String fileId = data.getStringValue();
            issuePolicyLogEntity.setStatus(consumeStatus);
            // 下载成功，更新数据库，绑定资源
            log.info("阳光财产安责保护伞的投保单号是  下载消息 fileId：{}", fileId);
            bindingResources(tbNo, fileId, issuePolicyLogEntity);
            return true;
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 适用于大地保险公司电子保单
     *
     * @param applicationFormCode
     * @param url
     * @return
     */
    private String getNewUrl(String applicationFormCode, String url) {
        url = url.replace("/download", "/download/link");
        try {
            try {
                Thread.sleep(80000);
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setReadTimeout(60000);
                connection.setConnectTimeout(10000);
                connection.setRequestMethod("GET");
                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = connection.getInputStream();
                    StringBuffer tStringBuffer = new StringBuffer();

                    BufferedReader tBufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    String sTempOneLine;
                    while ((sTempOneLine = tBufferedReader.readLine()) != null) {
                        tStringBuffer.append(sTempOneLine);
                    }
                    log.info("大地返回新电子保单路径: {}", tStringBuffer.toString());
                    return tStringBuffer.toString();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            log.error(applicationFormCode + ", 保单原地址为：" + url, e);
        }
        return url;
    }

    /**
     * 食品险（校园食品安全责任保险）
     *
     * @param rootElement
     * @return
     */
    private Boolean processSPX(Element rootElement, String ifCode) {
        Element respPacket = getRespPacket(rootElement);
        Element reqPacket = getReqPacket(rootElement);

        String currentTime = DateUtils.getCurrentTime();
        // 投保单号
        String tbNo = rootElement.element("ApplicationFormCode").getStringValue();
        // 保单号
        String policyNo = rootElement.element("PolicyNo").getStringValue();
        // 解析险种
        //String proCode = reqPacket.element("Body").element("Apply").element("PolicyType").getStringValue();
        String proCode = IssueEnum.getProCodeByIfCode(ifCode);

        log.debug("系统时间：{}, [食品险]下载电子保单 投保单号：{},保单号：{},产品险种编码：{}", currentTime, tbNo, policyNo, proCode);
        // 入库
        // 入库之前首先判断 是否已经入库  根据投保单号判断
        IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
        issueRecordEntity.setApplicationFormCode(tbNo);
        List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
        if (select != null && select.size() > 0) {
            log.info("系统时间：{} ,食品险投保单号是: {} 的消息发送重复", currentTime, tbNo);
            // 消息重复，消息直接消费完成。
            return true;
        }
        issueRecordEntity.setPolicyNo(policyNo);
        issueRecordEntity.setProCode(proCode);
        issueRecordEntity.setReqPacket(reqPacket.asXML());
        issueRecordEntity.setResPacket(respPacket.asXML());
        issueRecordEntity.setSendStatus("1");

        //0：成功  其余：失败
        String status = respPacket.element("Head").element("Code").getStringValue();
        if ("0".equals(status)) {
            status = "2";
        } else {
            status = "3";
        }
        // 数据中心返回 的投保单状态
        issueRecordEntity.setStatus(status);
        issueRecordEntity.setCreateTime(currentTime);
        issueRecordEntity.setUpdateTime(currentTime);
        issueRecordEntity.setIfCode(ifCode);
        issueRecordEntityMapper.insert(issueRecordEntity);
        if ("3".equals(status)) {
            // 出单失败或者重复出单，消息直接消费完成，在入库的逻辑后边。
            return true;
        }
        // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子保单
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";
        issuePolicyLogEntity.setApplicationFormCode(tbNo);
        issuePolicyLogEntity.setPolicyNo(policyNo);
        issuePolicyLogEntity.setType("1");
        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(proCode);

        //获取电子保单下载地址
        String policyUrl = respPacket.element("Body").element("Apply").element("PolicyUrl").getStringValue();
        //获取到重定向地址
       /* String newUrl = getNewUrl(tbNo, policyUrl);
        log.info("拼接电子保单 " + newUrl);*/
        // 拼装下载报文
        Map<String, String> map = new HashMap<>();
        map.put("ApplicationFormCode", tbNo);
        map.put("url", policyUrl);

        String param = JsonUtils.toJson(map);

        issuePolicyLogEntity.setParam(param);
        issuePolicyLogEntity.setTimes(0);
        issuePolicyLogEntity.setIfCode(ifCode);
        issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
        // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
        issueRecordEntity.setSendStatus("2");
        issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);

        //调用接口,请求数据交换中心，下载电子保单
        try {
            log.info("食品险的投保单号是: {}, 保单下载参数：{}", tbNo, param);
            // 请求下载保单，成功更新
            String seqNo = Long.toString(Math.abs(new Random().nextLong()));
            ResponseEntity<String> responseEntity = dexClient.text("edu", "20190802022", "1.0", seqNo, param);
            String ebody = responseEntity.getBody();
            log.info("食品险的投保单号是: {}, 保单下载返回值：{}, {}", tbNo, responseEntity.getStatusCodeValue(), ebody);
            Document doc = DocumentHelper.createDocument();
            doc = DocumentHelper.parseText(ebody);
            Element ebodyElement = doc.getRootElement();
            Element data = ebodyElement.element("data");
            consumeStatus = "2";
            if (data == null) {
                log.error("食品险请求下载电子保单失败");
                consumeStatus = "3";
            }
            String fileId = data.getStringValue();

            issuePolicyLogEntity.setStatus(consumeStatus);
            // 下载成功，更新数据库，绑定资源
            log.info("食品险的投保单号是  下载消息 fileId：{}", fileId);
            bindingResources(tbNo, fileId, issuePolicyLogEntity);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        sendEmail(tbNo, "21");
        Map<String, String> invoiceList = getAppcodeInvoiceType(tbNo);
        if (invoiceList.get("invoiceType").equals(InvoiceTypeEnum.ELECTRONIC_INVOICE.getType())) {
            //大地下载电子发票
            String invoiceUrl = respPacket.element("Body").element("Apply").element("InvoiceUrl").getStringValue();
            // 拼装下载报文
            Map<String, String> invoiceMap = new HashMap<>();
            invoiceMap.put("ApplicationFormCode", tbNo);
            invoiceMap.put("url", invoiceUrl);
            String invoiceParam = JsonUtils.toJson(invoiceMap);
            // 下载电子发票 拼装参数
            IssuePolicyLogEntity t = new IssuePolicyLogEntity();
            consumeStatus = "6";
            t.setApplicationFormCode(tbNo);
            t.setPolicyNo(policyNo);
            t.setType("3");
            t.setStatus(consumeStatus);
            t.setCreateTime(currentTime);
            t.setUpdateTime(currentTime);
            t.setProCode(proCode);
            t.setIfCode(ifCode);
            t.setParam(invoiceParam);
            t.setTimes(1);
            issuePolicyLogEntity.setIfCode(ifCode);
            // 电子发票的消费记录入库
            issuePolicyLogEntityMapper.insert(t);
            log.info(DateUtils.getCurrentTime() + "投保单号是" + tbNo + "下载发票开始，入参" + invoiceParam);
            String seqNo = Long.toString(Math.abs(new Random().nextLong()));
            ResponseEntity<String> responseEntity = null;
            try {
                responseEntity = dexClient.text("edu", "20190518021", "1.0", seqNo, invoiceParam);
                log.info(DateUtils.getCurrentTime() + "投保单号是" + tbNo + "下载发票结束，回参" + responseEntity.getStatusCodeValue() + "," + responseEntity.getBody());
                log.info(DateUtils.getCurrentTime() + "投保单号是" + tbNo + "下载发票结束，回参" + responseEntity.getStatusCodeValue() + "," + responseEntity.getBody());
                if (responseEntity != null) {
                    // 请求200，继续执行
                    if (responseEntity.getStatusCodeValue() != 200) {
                        log.error("请求下载电子发票失败");
                        t.setStatus("6");
                        t.setTimes(1);
                        t.setUpdateTime(currentTime);
                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                    } else {
                        String ebody = responseEntity.getBody();
                        Document doc = DocumentHelper.parseText(ebody);
                        Element ebodyElement = doc.getRootElement();
                        String code = ebodyElement.element("code").getStringValue();
                        if ("0000".equals(code)) {
                            String eInvoiceId = ebodyElement.element("data").getStringValue();
                            t.setStatus("2");
                            t.setEInvoiceId(eInvoiceId);
                            t.setTimes(1);
                            bindInvoice(t.getApplicationFormCode(), eInvoiceId, t);
                            log.info("大地电子发票 下载消息 fileId ：{}", eInvoiceId);
                        } else {
                            t.setStatus("6");
                            t.setTimes(1);
                            t.setUpdateTime(currentTime);
                            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                        }
                    }
                }
            } catch (Exception e) {
                log.error("调用dex服务失败,请重试");
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 徐州学平险（徐州学平意外险/徐州监护人责任险）
     *
     * @param rootElement
     * @return
     */
    private Boolean processXZXPX(Element rootElement, String ifCode) {
        Element respPacket = getRespPacket(rootElement);
        Element reqPacket = getReqPacket(rootElement);

        String currentTime = DateUtils.getCurrentTime();
        // 投保单号
        String tbNo = rootElement.element("ApplicationFormCode").getStringValue();
        // 保单号
        String policyNo = rootElement.element("PolicyNo").getStringValue();
        // 解析险种 19PR941489
        //String proCode = "19PR941489";
        String proCode = IssueEnum.getProCodeByIfCode(ifCode);
        // 108001 代表徐州学平意外险， 107001 代表徐州监护人责任险
        String transactionCode = reqPacket.element("head").element("transactionCode").getStringValue();

        log.debug("系统时间：{}, [徐州学平险]下载电子保单 投保单号：{},保单号：{},产品险种编码：{},徐州学平意外险(108001)/徐州监护人责任险(107001)：{}", currentTime, tbNo, policyNo, proCode, transactionCode);
        // 入库
        // 入库之前首先判断 是否已经入库  根据投保单号判断
        IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
        issueRecordEntity.setApplicationFormCode(tbNo);
        List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
        if (select != null && select.size() > 0) {
            log.info("系统时间：{} ,徐州学平险投保单号是: {} 的消息发送重复", currentTime, tbNo);
            // 消息重复，消息直接消费完成。
            return true;
        }
        issueRecordEntity.setPolicyNo(policyNo);
        issueRecordEntity.setProCode(proCode);
        issueRecordEntity.setReqPacket(reqPacket.asXML());
        issueRecordEntity.setResPacket(respPacket.asXML());
        issueRecordEntity.setSendStatus("1");

        //000000：成功  其余：失败
        String status = respPacket.element("head").element("responseCompleteMessageStatus").element("messageStatusCode").getStringValue();
        if ("000000".equals(status)) {
            status = "2";
        } else {
            status = "3";
        }
        // 数据中心返回 的投保单状态
        issueRecordEntity.setStatus(status);
        issueRecordEntity.setCreateTime(currentTime);
        issueRecordEntity.setUpdateTime(currentTime);
        issueRecordEntity.setIfCode(ifCode);
        issueRecordEntityMapper.insert(issueRecordEntity);
        if ("3".equals(status)) {
            // 出单失败或者重复出单，消息直接消费完成，在入库的逻辑后边。
            return true;
        }
        // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子保单
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";
        issuePolicyLogEntity.setApplicationFormCode(tbNo);
        issuePolicyLogEntity.setPolicyNo(policyNo);
        issuePolicyLogEntity.setType("1");
        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(proCode);

        //流水号
        String seqNo = Long.toString(Math.abs(new Random().nextLong()));
        //调用数据交换平台时入参ifCode
        String company = "";

        // 拼装下载报文
        Document doc = DocumentHelper.createDocument();
        Element info = doc.addElement("request");
        Element head = info.addElement("head");
        //转换编码
        //transactionCode = 108001(代表徐州学平意外险) 调用数据交换平台下载电子保单时传输编码为：108005
        //transactionCode = 107001(代表徐州学平意外险) 调用数据交换平台下载电子保单时传输编码为：107003
        if ("108001".equals(transactionCode)) {
            head.addElement("partnerCode");
            head.addElement("messageId").addText(seqNo);//流水号
            head.addElement("transactionCode").addText("108005");// 意外险标示 108005:代表徐州学平意外险
            head.addElement("transactionEffectiveDate").addText(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            head.addElement("user");
            head.addElement("password");
            Element body = info.addElement("body");
            Element epolicyInfoReprint = body.addElement("epolicyInfoReprint");
            epolicyInfoReprint.addElement("policyNo").addText(policyNo);
            epolicyInfoReprint.addElement("messageFlag");
            epolicyInfoReprint.addElement("emailFlag");
            epolicyInfoReprint.addElement("returnPDFFlag");

            company = "20190729002";
        } else if ("107001".equals(transactionCode)) {
            head.addElement("partnerCode");
            head.addElement("transactionCode").addText("107003");// 意外险标示 107003:代表徐州监护人责任险
            head.addElement("messageId").addText(seqNo);//流水号
            head.addElement("transactionEffectiveDate").addText(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            head.addElement("user");
            head.addElement("password");
            Element body = info.addElement("body");
            Element entity = body.addElement("entity");
            entity.addElement("plcNo").addText(policyNo);
            entity.addElement("elcMsgFlag");
            entity.addElement("elcMobile");
            entity.addElement("elcEmlFlag");
            entity.addElement("elcEmail");
            entity.addElement("returnPDF");

            company = "20190729003";
        }

        issuePolicyLogEntity.setParam(info.asXML());
        issuePolicyLogEntity.setTimes(0);
        issuePolicyLogEntity.setIfCode(ifCode);
        issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
        // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
        issueRecordEntity.setSendStatus("2");
        issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);

        //调用接口,请求数据交换中心，下载电子保单
        try {
            log.info("徐州学平险的投保单号是: {}, 保单下载参数：{}", tbNo, info.asXML());
            // 请求下载保单，成功更新
            ResponseEntity<String> responseEntity = dexClient.text("edu", company, "1.0", seqNo, info.asXML());
            String ebody = responseEntity.getBody();
            log.info("徐州学平险的投保单号是: {}, 保单下载返回值：{}, {}", tbNo, responseEntity.getStatusCodeValue(), ebody);

            Document resultDoc = DocumentHelper.createDocument();
            resultDoc = DocumentHelper.parseText(ebody);
            Element ebodyElement = resultDoc.getRootElement();
            Element data = ebodyElement.element("data");
            consumeStatus = "2";
            if (data == null) {
                log.error("徐州学平险请求下载电子保单失败");
                consumeStatus = "3";
            }
            String fileId = data.getStringValue();

            issuePolicyLogEntity.setStatus(consumeStatus);
            // 下载成功，更新数据库，绑定资源
            log.info("徐州学平险的投保单号是  下载消息 fileId：{}", fileId);
            bindingResources(tbNo, fileId, issuePolicyLogEntity);
            return true;
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 实责校责（大地）
     *
     * @param rootElement
     * @return
     */
    private Boolean processSZXZDD(Element rootElement, String ifCode) {
        Element respPacket = getRespPacket(rootElement);
        Element reqPacket = getReqPacket(rootElement);

        String currentTime = DateUtils.getCurrentTime();


        List<Element> respChildElements = respPacket.element("Body").elements();
        for (Element child : respChildElements) {
            //0：成功  其余：失败
            String status = respPacket.element("Head").element("Code").getStringValue();
            // 投保单号
            String tbNo = child.element("AppCode").getStringValue();
            // 保单号
            String policyNo = child.element("PolicyCode").getStringValue();
            // 解析险种
            List<Element> reqChildElements = reqPacket.element("Body").elements();
            String proCode = "";
            for (Element reqChild : reqChildElements) {
                String applyId = reqChild.element("ApplyId").getStringValue();
                if (tbNo.equals(applyId)) {
                    String mainType = reqChild.element("MainType").getStringValue();
                    proCode = IssueEnum.getProCodeByIfCode(ifCode + mainType);
                }
            }

            log.debug("系统时间：{}, [实责校责（大地）]下载电子保单 投保单号：{},保单号：{},产品险种编码：{}", currentTime, tbNo, policyNo, proCode);
            // 入库
            // 入库之前首先判断 是否已经入库  根据投保单号判断
            IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
            issueRecordEntity.setApplicationFormCode(tbNo);
            List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
            if (select != null && select.size() > 0) {
                log.info("系统时间：{}, 实责校责（大地）投保单号是：{} 的消息发送重复", currentTime, tbNo);
                // 消息重复，消息直接消费完成。
                break;
            }
            issueRecordEntity.setPolicyNo(policyNo);
            issueRecordEntity.setProCode(proCode);
            issueRecordEntity.setReqPacket(reqPacket.asXML());
            issueRecordEntity.setResPacket(respPacket.asXML());
            issueRecordEntity.setSendStatus("1");

            //0：成功  其余：失败
            if ("0".equals(status)) {
                status = "2";
            } else {
                status = "3";
            }
            // 数据中心返回 的投保单状态
            issueRecordEntity.setStatus(status);
            issueRecordEntity.setCreateTime(currentTime);
            issueRecordEntity.setUpdateTime(currentTime);
            issueRecordEntity.setIfCode(ifCode);
            issueRecordEntityMapper.insert(issueRecordEntity);
            if ("3".equals(status)) {
                // 出单失败或者重复出单，消息直接消费完成，在入库的逻辑后边。
                break;
            }
            // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子保单
            IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
            String consumeStatus = "1";
            issuePolicyLogEntity.setApplicationFormCode(tbNo);
            issuePolicyLogEntity.setPolicyNo(policyNo);
            issuePolicyLogEntity.setType("1");
            issuePolicyLogEntity.setStatus(consumeStatus);
            issuePolicyLogEntity.setCreateTime(currentTime);
            issuePolicyLogEntity.setUpdateTime(currentTime);
            issuePolicyLogEntity.setProCode(proCode);

            String policyUrl = child.element("PolicyUrl").getStringValue();
            /*String newUrl = getNewUrl(tbNo, policyUrl);
            log.info("实责校责（大地）拼接电子保单 " + newUrl);*/

            // 拼装下载报文
            Map<String, String> map = new HashMap<>();
            map.put("ApplicationFormCode", tbNo);
            map.put("url", policyUrl);

            String param = JsonUtils.toJson(map);

            issuePolicyLogEntity.setParam(param);
            issuePolicyLogEntity.setTimes(0);
            issuePolicyLogEntity.setIfCode(ifCode);
            issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
            // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
            issueRecordEntity.setSendStatus("2");
            issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);

            //调用接口,请求数据交换中心，下载电子保单
            try {
                log.info("实责校责（大地）的投保单号是: {}, 保单下载参数：{}", tbNo, param);
                // 请求下载保单，成功更新
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = dexClient.text("edu", "20190518021", "1.0", seqNo, param);
                String ebody = responseEntity.getBody();
                log.info("实责校责（大地）的投保单号是: {}, 保单下载返回值：{}, {}", tbNo, responseEntity.getStatusCodeValue(), responseEntity.getBody());

                Document resultDoc = DocumentHelper.createDocument();
                resultDoc = DocumentHelper.parseText(ebody);
                Element ebodyElement = resultDoc.getRootElement();
                Element data = ebodyElement.element("data");
                consumeStatus = "2";
                if (data == null) {
                    log.error("实责校责（大地）请求下载电子保单失败");
                    consumeStatus = "3";
                }
                String fileId = data.getStringValue();
                issuePolicyLogEntity.setStatus(consumeStatus);
                // 下载成功，更新数据库，绑定资源
                log.info("实责校责（大地）的投保单号是  下载消息 fileId：{}", fileId);
                bindingResources(tbNo, fileId, issuePolicyLogEntity);
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            sendEmail(tbNo, "21");
            Map<String, String> invoiceList = getAppcodeInvoiceType(tbNo);
            if (invoiceList.get("invoiceType").equals(InvoiceTypeEnum.ELECTRONIC_INVOICE.getType())) {
                String invoiceUrl = child.element("InvoiceUrl").getStringValue();
                // 拼装下载报文
                Map<String, String> invoiceMap = new HashMap<>();
                invoiceMap.put("ApplicationFormCode", tbNo);
                invoiceMap.put("url", invoiceUrl);
                String invoiceParam = JsonUtils.toJson(invoiceMap);
                // 下载电子发票 拼装参数
                IssuePolicyLogEntity t = new IssuePolicyLogEntity();
                consumeStatus = "6";
                t.setApplicationFormCode(tbNo);
                t.setPolicyNo(policyNo);
                t.setType("3");
                t.setStatus(consumeStatus);
                t.setCreateTime(currentTime);
                t.setUpdateTime(currentTime);
                t.setProCode(proCode);
                t.setIfCode(ifCode);
                t.setParam(invoiceParam);
                t.setTimes(1);
                issuePolicyLogEntity.setIfCode(ifCode);
                // 电子发票的消费记录入库
                issuePolicyLogEntityMapper.insert(t);
                log.info(DateUtils.getCurrentTime() + "投保单号是" + tbNo + "下载发票开始，入参" + invoiceParam);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                try {
                    responseEntity = dexClient.text("edu", "20190518021", "1.0", seqNo, invoiceParam);
                    log.info(DateUtils.getCurrentTime() + "投保单号是" + tbNo + "下载发票结束，回参" + responseEntity.getStatusCodeValue() + "," + responseEntity.getBody());
                    if (responseEntity != null) {
                        // 请求200，继续执行
                        if (responseEntity.getStatusCodeValue() != 200) {
                            log.error("请求下载电子发票失败");
                            t.setStatus("6");
                            t.setTimes(1);
                            t.setUpdateTime(currentTime);
                            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                        } else {
                            String ebody = responseEntity.getBody();
                            Document doc = DocumentHelper.parseText(ebody);
                            Element ebodyElement = doc.getRootElement();
                            String code = ebodyElement.element("code").getStringValue();
                            if ("0000".equals(code)) {
                                String eInvoiceId = ebodyElement.element("data").getStringValue();
                                t.setStatus("2");
                                t.setEInvoiceId(eInvoiceId);
                                t.setTimes(1);
                                bindInvoice(t.getApplicationFormCode(), eInvoiceId, t);
                                log.info("大地电子发票 下载消息 fileId ：{}", eInvoiceId);
                            } else {
                                t.setStatus("6");
                                t.setTimes(1);
                                t.setUpdateTime(currentTime);
                                issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("调用dex服务失败,请重试");
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    /**
     * 实责校责（太平/中华联合/国寿财）
     *
     * @param rootElement
     * @return
     */
    private Boolean processSZXZ(Element rootElement, String ifCode) {
        Element respPacket = getRespPacket(rootElement);
        Element reqPacket = getReqPacket(rootElement);

        String currentTime = DateUtils.getCurrentTime();

        List<Element> respChildElements = respPacket.element("Body").elements();
        String status = null;
        String tbNo = null;
        String policyNo = null;
        String amount = null;
        for (Element child : respChildElements) {
            //0：成功  其余：失败
            if (ifCode.equals("20190731001")) {
                status = respPacket.element("Head").element("Code").getStringValue();
                tbNo = child.element("AppCode").getStringValue();
                // 保单号
                policyNo = child.element("PolicyCode").getStringValue();
            } else {
                status = respPacket.element("Head").element("ResponseCode").getStringValue();
                // 投保单号
                tbNo = child.element("ApplyId").getStringValue();
                // 保单号
                policyNo = child.element("PolicyNo").getStringValue();
                amount = child.element("Fee").getStringValue();
            }
            // 解析险种
            List<Element> reqChildElements = reqPacket.element("Body").elements();
            String proCode = "";
            String mainType = "";
            String policyHolderName = "";
            String insurantName = "";
            String holderEmail = "";
            for (Element reqChild : reqChildElements) {
                String applyId = reqChild.element("ApplyId").getStringValue();
                if (tbNo.equals(applyId)) {
                    mainType = reqChild.element("MainType").getStringValue();
                    proCode = IssueEnum.getProCodeByIfCode(ifCode + mainType);
                    policyHolderName = reqChild.element("PolicyHolder").element("Name").getStringValue();
                    insurantName = reqChild.element("InsurantInfo").element("Name").getStringValue();
                    holderEmail = reqChild.element("PolicyHolder").element("ConEmail").getStringValue();
                    break;
                }
            }

            log.debug("系统时间：{}, [实责校责]下载电子保单 投保单号：{},保单号：{},产品险种编码：{}", currentTime, tbNo, policyNo, proCode);
            // 入库
            // 入库之前首先判断 是否已经入库  根据投保单号判断
            IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
            issueRecordEntity.setApplicationFormCode(tbNo);
            List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
            if (select != null && select.size() > 0) {
                log.info("系统时间：{}, 实责校责投保单号是：{} 的消息发送重复", currentTime, tbNo);
                // 消息重复，消息直接消费完成。
                continue;
            }
            issueRecordEntity.setPolicyNo(policyNo);
            issueRecordEntity.setProCode(proCode);
            issueRecordEntity.setMainType(mainType);
            issueRecordEntity.setReqPacket(reqPacket.asXML());
            issueRecordEntity.setResPacket(respPacket.asXML());
            issueRecordEntity.setSendStatus("1");

            //0：成功  其余：失败
            if ("0".equals(status)) {
                status = "2";
            } else {
                status = "3";
            }
            // 数据中心返回 的投保单状态
            issueRecordEntity.setStatus(status);
            issueRecordEntity.setCreateTime(currentTime);
            issueRecordEntity.setUpdateTime(currentTime);
            issueRecordEntity.setIfCode(ifCode);
            issueRecordEntityMapper.insert(issueRecordEntity);
            if ("3".equals(status)) {
                // 出单失败或者重复出单，消息直接消费完成，在入库的逻辑后边。
                break;
            }
            // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子保单
            IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
            String consumeStatus = "1";
            issuePolicyLogEntity.setApplicationFormCode(tbNo);
            issuePolicyLogEntity.setPolicyNo(policyNo);
            issuePolicyLogEntity.setType("1");
            issuePolicyLogEntity.setStatus(consumeStatus);
            issuePolicyLogEntity.setCreateTime(currentTime);
            issuePolicyLogEntity.setUpdateTime(currentTime);
            issuePolicyLogEntity.setMainType(mainType);
            issuePolicyLogEntity.setProCode(proCode);

            // 拼装下载报文
            Document doc = DocumentHelper.createDocument();
            Element info = null;
            if (ifCode.equals("20190827001")) {
                info = DocumentHelper.createElement("EduApply");
                doc = DocumentHelper.createDocument(info);
                Element head = info.addElement("head");
                Element userId = head.addElement("UserId"); //
                userId.setText("100000");
                Element commandId = head.addElement("CommandId");
                commandId.setText("ERA0001");
                Element seqNo = head.addElement("SeqNo");
                seqNo.setText(tbNo);
                Element body = info.addElement("BODY");
                Element policyNoOn = body.addElement("PolicyNo");
                policyNoOn.setText(policyNo);
            } else {
                String policyUrl = child.element("PolicyUrl").getStringValue();
                info = doc.addElement("body");
                info.addElement("url").addText(policyUrl);
            }

            issuePolicyLogEntity.setParam(info.asXML());
            issuePolicyLogEntity.setTimes(0);
            issuePolicyLogEntity.setIfCode(ifCode);
            issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
            // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
            issueRecordEntity.setSendStatus("2");
            issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);
            String eUrl = null;
            //调用接口,请求数据交换中心，下载电子保单
            try {
                //国寿财电子保单需要特殊处理
                if (ifCode.equals("20190827001")) {
                    eUrl = doc.asXML();
                } else {
                    eUrl = info.asXML().replace("&amp;", "&");
                }
                log.info("实责校责的投保单号是: {}, 保单下载参数：{}", tbNo, eUrl);
                // 请求下载保单，成功更新
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                if (ifCode.equals("20190827001")) {
                    responseEntity = dexClient.text("edu", "20191118001", "1.0", seqNo, eUrl);
                } else {
                    responseEntity = dexClient.text("edu", "20190726008", "1.0", seqNo, eUrl);

                }
                String ebody = responseEntity.getBody();
                log.info("实责校责的投保单号是: {}, 保单下载返回值：{}, {}", tbNo, responseEntity.getStatusCodeValue(), responseEntity.getBody());

                consumeStatus = "2";
                if (ebody == null) {
                    log.error("实责校责请求下载电子保单失败");
                    consumeStatus = "3";
                }
                if (ifCode.equals("20190827001")) {
                    Document resultDoc = DocumentHelper.createDocument();
                    resultDoc = DocumentHelper.parseText(ebody);
                    Element ebodyElement = resultDoc.getRootElement();
                    Element data = ebodyElement.element("data");
                    ebody = data.getStringValue();
                }
                issuePolicyLogEntity.setStatus(consumeStatus);
                // 下载成功，更新数据库，绑定资源
                log.info("实责校责的投保单号是  下载消息 fileId：{}", ebody);
                bindingResources(tbNo, ebody, issuePolicyLogEntity);
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            sendEmail(tbNo, "21");
            Map<String, String> invoiceList = getAppcodeInvoiceType(tbNo);
            //太平洋下载电子发票
            if (ifCode.equals("20190726017") && invoiceList.get("invoiceType").equals(InvoiceTypeEnum.ELECTRONIC_INVOICE.getType())) { // 有发票
                //todo 7-13 11:58
                // 下载电子发票 拼装参数
                IssuePolicyLogEntity t = new IssuePolicyLogEntity();
                consumeStatus = "6";
                t.setApplicationFormCode(tbNo);
                t.setPolicyNo(policyNo);
                t.setType("3");
                t.setStatus(consumeStatus);
                t.setCreateTime(currentTime);
                t.setUpdateTime(currentTime);
                t.setProCode(proCode);
                t.setMainType(mainType);
                t.setIfCode(ifCode);
                doc = DocumentHelper.createDocument();
                // 组装电子发票的报文

                //获取纳税人识别码
                String taxpayerIdentificationNumber = invoiceList.get("taxpayerIdentificationNumber");
                String title = invoiceList.get("title");
                info = doc.addElement("POLICYINFO");
                doc.setRootElement(info);
                Element policyNos = info.addElement("policyNo").addText(policyNo);  //保单号
                Element payeeName = info.addElement("payeeName").addText(title); //开票人信息
                Element taxPayerNo = info.addElement("taxPayerNo").addText(taxpayerIdentificationNumber); //组织机构代码证
                String isPayeeType = "0";
                //判断是否是投保人还是被保险人
                if (!policyHolderName.equals(insurantName)) {
                    isPayeeType = "1";
                }
                Element payeeType = info.addElement("payeeType").addText(isPayeeType); //发票抬头类型
                t.setParam(info.asXML());
                t.setTimes(1);
                issuePolicyLogEntity.setIfCode(ifCode);
                // 电子发票的消费记录入库
                issuePolicyLogEntityMapper.insert(t);
                log.info(DateUtils.getCurrentTime() + "投保单号是" + tbNo + "下载发票开始，入参" + info.asXML());
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                try {
                    responseEntity = dexClient.text("edu", "202007141606280", "1.0", seqNo, info.asXML());
                    log.info(DateUtils.getCurrentTime() + "投保单号是" + tbNo + "下载发票结束，回参" + responseEntity.getStatusCodeValue() + "," + responseEntity.getBody());
                    if (responseEntity != null) {
                        // 请求200，继续执行
                        if (responseEntity.getStatusCodeValue() != 200) {
                            log.error("请求下载电子发票失败");
                            t.setStatus("6");
                            t.setTimes(1);
                            t.setUpdateTime(currentTime);
                            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                        } else {
                            String fileId = responseEntity.getBody();
                            t.setStatus("2");
                            t.setUpdateTime(currentTime);
                            t.setEInvoiceId(fileId);
                            // 下载成功，更新数据库，绑定资源
                            log.info("太平电子发票 下载消息 fileId ：{}", fileId);
                            bindInvoice(tbNo, fileId, t);
                        }
                    }
                } catch (Exception e) {
                    log.error("调用dex服务失败,请重试");
                    e.printStackTrace();
                }
            }
            if (ifCode.equals("20190827001") && invoiceList.get("invoiceType").equals(InvoiceTypeEnum.ELECTRONIC_INVOICE.getType())) { // 有发票
                //如果是国寿财调用另一套下载电子发票方法
                //电子发票开票申请入参
                NewElecInvoicePrintRequestVO newElecInvoicePrintRequestVO = new NewElecInvoicePrintRequestVO();
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                newElecInvoicePrintRequestVO.setMerchantNo("P192"); //这个保险公司提供
                newElecInvoicePrintRequestVO.setRequestType(InvoiceRequestTypeEnum.APPLY_INVOICE.getType());
                newElecInvoicePrintRequestVO.setInvoicePrintType(InvoiceTypeEnum.BLUE_INVOICE.getType());
                newElecInvoicePrintRequestVO.setRequestId(seqNo);
                newElecInvoicePrintRequestVO.setBusinessType("1"); //1、联共保主方+代从方全额开票  2、联共保主方全额开票 3、联共保其他开票场景（需调1.4接口获取联共保开票信息后按自己场景组织开票数据）

                //保单信息
                List<NewElecPolicyInfoList> newElecPolicyInfoVOlist = new ArrayList<>();
                NewElecPolicyInfoList newElecPolicyInfoList = new NewElecPolicyInfoList();
                newElecPolicyInfoList.setCertiNo(policyNo);
                newElecPolicyInfoList.setCertiTypeCode("P");

                newElecPolicyInfoList.setOpenVisaFee(amount); //金额需要去获取
                newElecPolicyInfoVOlist.add(newElecPolicyInfoList);
                //发票信息
                String title = invoiceList.get("title");
                List<NewElecInvoiceInfoVO> newElecInvoiceInfoVOS = new ArrayList<>();
                NewElecInvoiceInfoVO newElecInvoiceInfoVO = new NewElecInvoiceInfoVO();
                newElecInvoiceInfoVO.setInvoiceTitle(title);
                newElecInvoiceInfoVO.setEmail(holderEmail);
                newElecInvoiceInfoVO.setVisaFee(amount);
                String invoiceObjectType = "1";
                //获取到投保人名称和发票信息,如果是一致,说明是投保人类型
                if (!policyHolderName.equals(insurantName)) {
                    invoiceObjectType = "2";
                }
                newElecInvoiceInfoVO.setInvoiceObjectType(invoiceObjectType);
                newElecInvoiceInfoVO.setTaxPayerNo(invoiceList.get("taxpayerIdentificationNumber"));
                newElecInvoiceInfoVO.setBuyerAddress(invoiceList.get("bankAddress"));
                newElecInvoiceInfoVO.setBuyerTelePhone(invoiceList.get("mobile"));
                newElecInvoiceInfoVO.setBuyerBankName(invoiceList.get("bankName"));
                newElecInvoiceInfoVO.setBuyerAccountCode(invoiceList.get("bankNo"));
                newElecInvoiceInfoVO.setNewElecPolicyInfoList(newElecPolicyInfoVOlist);
                newElecInvoiceInfoVOS.add(newElecInvoiceInfoVO);
                newElecInvoicePrintRequestVO.setNewElecInvoiceInfoList(newElecInvoiceInfoVOS);
                // 下载电子发票 拼装参数
                IssuePolicyLogEntity t = new IssuePolicyLogEntity();
                consumeStatus = "6";
                t.setApplicationFormCode(tbNo);
                t.setPolicyNo(policyNo);
                t.setType("3");
                t.setStatus(consumeStatus);
                t.setCreateTime(currentTime);
                t.setUpdateTime(currentTime);
                t.setProCode(proCode);
                t.setMainType(mainType);
                t.setIfCode(ifCode);
                String param = JSON.toJSONString(newElecInvoicePrintRequestVO);
                t.setParam(param);
                t.setTimes(1);
                issuePolicyLogEntity.setIfCode(ifCode);
                // 电子发票的消费记录入库
                issuePolicyLogEntityMapper.insert(t);
                log.info(DateUtils.getCurrentTime() + "投保单号是" + tbNo + "发票申请开始，入参" + param);
                ResponseEntity<String> responseEntity = null;
                try {
                    responseEntity = dexClient.text("edu", "202012091335240", "1.0", seqNo, param);
                    log.info(DateUtils.getCurrentTime() + "投保单号是" + tbNo + "发票申请结束，回参" + responseEntity.getStatusCodeValue() + "," + responseEntity.getBody());
                    if (responseEntity.getBody().equals("Effective")) {
                        //判断返回的是够是申请成功,如果开具成功Effective,自己拼接下载地址进行下载
                        String url = getGSInvoiceAddress(policyNo);
                        //根据地址下载电子发票
                        Map<String, String> invoiceMap = new HashMap<>();
                        invoiceMap.put("ApplicationFormCode", tbNo);
                        invoiceMap.put("url", url);
                        String invoiceParam = JsonUtils.toJson(invoiceMap);
                        log.info(DateUtils.getCurrentTime() + "投保单号是" + tbNo + "下载发票开始，入参" + invoiceParam);
                        responseEntity = dexClient.text("edu", "20190518021", "1.0", seqNo, invoiceParam);
                        log.info(DateUtils.getCurrentTime() + "投保单号是" + tbNo + "下载发票结束，回参" + responseEntity.getStatusCodeValue() + "," + responseEntity.getBody());
                        if (responseEntity != null) {
                            // 请求200，继续执行
                            if (responseEntity.getStatusCodeValue() != 200) {
                                log.error("请求下载电子发票失败");
                                t.setStatus("6");
                                t.setTimes(1);
                                t.setUpdateTime(currentTime);
                                issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                            } else {
                                String ebody = responseEntity.getBody();
                                doc = DocumentHelper.parseText(ebody);
                                Element ebodyElement = doc.getRootElement();
                                String code = ebodyElement.element("code").getStringValue();
                                if ("0000".equals(code)) {
                                    String eInvoiceId = ebodyElement.element("data").getStringValue();
                                    t.setStatus("2");
                                    t.setEInvoiceId(eInvoiceId);
                                    t.setTimes(1);
                                    bindInvoice(t.getApplicationFormCode(), eInvoiceId, t);
                                    log.info("国寿电子发票 下载消息 fileId ：{}", eInvoiceId);
                                } else {
                                    t.setStatus("6");
                                    t.setTimes(1);
                                    t.setUpdateTime(currentTime);
                                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("调用dex服务失败,请重试");
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    //拼接国寿下载发票地址
    public String getGSInvoiceAddress(String policyNo) {
        String key = policyNo + "gpic@2018!";
        String sign = MD5Utils.MD5(key);
        String url = configurationParameters.getDownInvoiceUrl() + "sign=00" + "edu" + sign + "&PolicyNo=" + policyNo;
        return url;
    }

    /**
     * 食品险（太平）
     *
     * @param rootElement
     * @return
     */
    private Boolean processSPXTP(Element rootElement, String ifCode) {
        Element respPacket = getRespPacket(rootElement);
        Element reqPacket = getReqPacket(rootElement);

        String currentTime = DateUtils.getCurrentTime();
        // 投保单号
        String tbNo = rootElement.element("ApplicationFormCode").getStringValue();
        // 保单号
        String policyNo = rootElement.element("PolicyNo").getStringValue();

        String policyHolderName = reqPacket.element("Body").element("Apply").element("HolderInfo").element("Name").getStringValue();
        String insurantName = reqPacket.element("Body").element("Apply").element("InsuredInfo").element("Name").getStringValue();
        String holderEmail = reqPacket.element("Body").element("Apply").element("HolderInfo").element("ConEmail").getStringValue();
        String amount = reqPacket.element("Body").element("Apply").element("RiskInfo").element("totalPremium").getStringValue();
        // 解析险种
        //String proCode = reqPacket.element("Body").element("Apply").element("PolicyType").getStringValue();
        String proCode = IssueEnum.getProCodeByIfCode(ifCode);

        log.debug("系统时间：{}, [食品险（太平）]下载电子保单 投保单号：{},保单号：{},产品险种编码：{}", currentTime, tbNo, policyNo, proCode);
        // 入库
        // 入库之前首先判断 是否已经入库  根据投保单号判断
        IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
        issueRecordEntity.setApplicationFormCode(tbNo);
        List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
        if (select != null && select.size() > 0) {
            log.info("系统时间：{} ,食品险（太平）投保单号是: {} 的消息发送重复", currentTime, tbNo);
            // 消息重复，消息直接消费完成。
            return true;
        }
        issueRecordEntity.setPolicyNo(policyNo);
        issueRecordEntity.setProCode(proCode);
        issueRecordEntity.setReqPacket(reqPacket.asXML());
        issueRecordEntity.setResPacket(respPacket.asXML());
        issueRecordEntity.setSendStatus("1");

        //0：成功  其余：失败
        String status = null;
        if (ifCode.equals("20190909101")) {
            status = respPacket.element("Head").element("ResponseCode").getStringValue();
        } else {
            status = respPacket.element("Head").element("Code").getStringValue();
        }
        if ("0".equals(status)) {
            status = "2";
        } else {
            status = "3";
        }
        // 数据中心返回 的投保单状态
        issueRecordEntity.setStatus(status);
        issueRecordEntity.setCreateTime(currentTime);
        issueRecordEntity.setUpdateTime(currentTime);
        issueRecordEntity.setIfCode(ifCode);
        issueRecordEntityMapper.insert(issueRecordEntity);
        if ("3".equals(status)) {
            // 出单失败或者重复出单，消息直接消费完成，在入库的逻辑后边。
            return true;
        }
        // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子保单
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";
        issuePolicyLogEntity.setApplicationFormCode(tbNo);
        issuePolicyLogEntity.setPolicyNo(policyNo);
        issuePolicyLogEntity.setType("1");
        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(proCode);


        // 拼装下载报文
        Document doc = DocumentHelper.createDocument();
        Element info = doc.addElement("body");

        //info.addElement("url").addText("https://iepolicy.sinosig.com/digitalBill_download/downloadPolicy.action?file=201908211045-247a5479-9f32-4036-943c-f55c052a73c9");
        if (ifCode.equals("20190909101")) {
            info = DocumentHelper.createElement("EduApply");
            doc = DocumentHelper.createDocument(info);
            Element head = info.addElement("head");
            Element userId = head.addElement("UserId"); //
            userId.setText("100000");
            Element commandId = head.addElement("CommandId");
            commandId.setText("ERA0001");
            Element seqNo = head.addElement("SeqNo");
            seqNo.setText(tbNo);
            Element body = info.addElement("BODY");
            Element policyNoOn = body.addElement("PolicyNo");
            policyNoOn.setText(policyNo);
        } else {
            //获取电子保单下载地址
            String policyUrl = respPacket.element("Body").element("PolicyUrl").getStringValue();
            info.addElement("url").addText(policyUrl);
        }
        issuePolicyLogEntity.setParam(info.asXML());
        issuePolicyLogEntity.setTimes(0);
        issuePolicyLogEntity.setIfCode(ifCode);
        issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
        // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
        issueRecordEntity.setSendStatus("2");
        issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);
        String eUrl = null;
        //调用接口,请求数据交换中心，下载电子保单
        try {
            if (ifCode.equals("20190909101")) {
                eUrl = info.asXML();
            } else {
                eUrl = info.asXML().replace("&amp;", "&");
            }
            log.info("食品险（太平）的投保单号是: {}, 保单下载参数：{}", tbNo, eUrl);
            // 请求下载保单，成功更新
            String seqNo = Long.toString(Math.abs(new Random().nextLong()));
            ResponseEntity<String> responseEntity = null;
            if (ifCode.equals("20190909101")) {
                responseEntity = dexClient.text("edu", "20191118001", "1.0", seqNo, eUrl);

            } else {
                responseEntity = dexClient.text("edu", "20190802032", "1.0", seqNo, eUrl);

            }
            String ebody = responseEntity.getBody();
            log.info("食品险（太平）的投保单号是: {}, 保单下载返回值：{}, {}", tbNo, responseEntity.getStatusCodeValue(), ebody);
            consumeStatus = "2";
            if (ebody == null) {
                log.error("食品险（太平）请求下载电子保单失败");
                consumeStatus = "3";
            }

            issuePolicyLogEntity.setStatus(consumeStatus);
            if (ifCode.equals("20190909101")) {
                Document resultDoc = DocumentHelper.createDocument();
                resultDoc = DocumentHelper.parseText(ebody);
                Element ebodyElement = resultDoc.getRootElement();
                Element data = ebodyElement.element("data");
                ebody = data.getStringValue();
            }
            // 下载成功，更新数据库，绑定资源
            log.info("食品险（太平）的投保单号是  下载消息 fileId：{}", ebody);
            bindingResources(tbNo, ebody, issuePolicyLogEntity);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        sendEmail(tbNo, "21");
        Map<String, String> invoiceList = getAppcodeInvoiceType(tbNo);
        if (ifCode.equals("20190726007") && invoiceList.get("invoiceType").equals(InvoiceTypeEnum.ELECTRONIC_INVOICE.getType())) { // 有发票

            //todo 7-13 11:58
            // 下载电子发票 拼装参数
            IssuePolicyLogEntity t = new IssuePolicyLogEntity();
            consumeStatus = "6";
            t.setApplicationFormCode(tbNo);
            t.setPolicyNo(policyNo);
            t.setType("3");
            t.setStatus(consumeStatus);
            t.setCreateTime(currentTime);
            t.setUpdateTime(currentTime);
            t.setProCode(proCode);
            t.setIfCode(ifCode);
            doc = DocumentHelper.createDocument();
            //获取纳税人识别码
            String taxpayerIdentificationNumber = invoiceList.get("taxpayerIdentificationNumber");
            String title = invoiceList.get("title");
            info = doc.addElement("POLICYINFO");
            doc.setRootElement(info);
            Element policyNos = info.addElement("policyNo").addText(policyNo);  //保单号
            Element payeeName = info.addElement("payeeName").addText(title); //开票人信息
            Element taxPayerNo = info.addElement("taxPayerNo").addText(taxpayerIdentificationNumber); //组织机构代码证
            String isPayeeType = "0";
            //判断是否是投保人还是被保险人
            if (!policyHolderName.equals(insurantName)) {
                isPayeeType = "1";
            }
            Element payeeType = info.addElement("payeeType").addText(isPayeeType); //发票抬头类型
            t.setParam(info.asXML());
            t.setTimes(1);
            issuePolicyLogEntity.setIfCode(ifCode);
            // 电子发票的消费记录入库
            issuePolicyLogEntityMapper.insert(t);
            log.info(DateUtils.getCurrentTime() + "投保单号是" + tbNo + "下载发票开始，入参" + info.asXML());
            String seqNo = Long.toString(Math.abs(new Random().nextLong()));
            ResponseEntity<String> responseEntity = null;
            try {
                responseEntity = dexClient.text("edu", "202007141606280", "1.0", seqNo, info.asXML());
                log.info(DateUtils.getCurrentTime() + "投保单号是" + tbNo + "下载发票结束，回参" + responseEntity.getStatusCodeValue() + "," + responseEntity.getBody());
                if (responseEntity != null) {
                    // 请求200，继续执行
                    if (responseEntity.getStatusCodeValue() != 200) {
                        log.error("请求下载电子发票失败");
                        t.setStatus("6");
                        t.setTimes(1);
                        t.setUpdateTime(currentTime);
                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                    } else {
                        String fileId = responseEntity.getBody();
                        t.setStatus("2");
                        t.setUpdateTime(currentTime);
                        t.setEInvoiceId(fileId);
                        // 下载成功，更新数据库，绑定资源
                        log.info("太平电子发票 下载消息 fileId ：{}", fileId);
                        bindInvoice(tbNo, fileId, t);
                    }
                }
            } catch (Exception e) {
                log.error("调用dex服务失败,请重试");
                e.printStackTrace();
            }
        }
        if (ifCode.equals("20190909101") && invoiceList.get("invoiceType").equals(InvoiceTypeEnum.ELECTRONIC_INVOICE.getType())) { // 有发票
            //如果是国寿财调用另一套下载电子发票方法
            //电子发票开票申请入参
            NewElecInvoicePrintRequestVO newElecInvoicePrintRequestVO = new NewElecInvoicePrintRequestVO();
            String seqNo = Long.toString(Math.abs(new Random().nextLong()));
            newElecInvoicePrintRequestVO.setMerchantNo("P192"); //这个保险公司提供
            newElecInvoicePrintRequestVO.setRequestType(InvoiceRequestTypeEnum.APPLY_INVOICE.getType());
            newElecInvoicePrintRequestVO.setInvoicePrintType(InvoiceTypeEnum.BLUE_INVOICE.getType());
            newElecInvoicePrintRequestVO.setRequestId(seqNo);
            newElecInvoicePrintRequestVO.setBusinessType("1"); //1、联共保主方+代从方全额开票  2、联共保主方全额开票 3、联共保其他开票场景（需调1.4接口获取联共保开票信息后按自己场景组织开票数据）

            //保单信息
            List<NewElecPolicyInfoList> newElecPolicyInfoVOlist = new ArrayList<>();
            NewElecPolicyInfoList newElecPolicyInfoList = new NewElecPolicyInfoList();
            newElecPolicyInfoList.setCertiNo(policyNo);
            newElecPolicyInfoList.setCertiTypeCode("P");

            newElecPolicyInfoList.setOpenVisaFee(amount); //金额需要去获取
            newElecPolicyInfoVOlist.add(newElecPolicyInfoList);
            //发票信息
            String title = invoiceList.get("title");
            List<NewElecInvoiceInfoVO> newElecInvoiceInfoVOS = new ArrayList<>();
            NewElecInvoiceInfoVO newElecInvoiceInfoVO = new NewElecInvoiceInfoVO();
            newElecInvoiceInfoVO.setInvoiceTitle(title);
            newElecInvoiceInfoVO.setEmail(holderEmail);
            newElecInvoiceInfoVO.setVisaFee(amount);
            String invoiceObjectType = "1";
            //获取到投保人名称和发票信息,如果是一致,说明是投保人类型
            if (!policyHolderName.equals(insurantName)) {
                invoiceObjectType = "2";
            }
            newElecInvoiceInfoVO.setInvoiceObjectType(invoiceObjectType);
            newElecInvoiceInfoVO.setTaxPayerNo(invoiceList.get("taxpayerIdentificationNumber"));
            newElecInvoiceInfoVO.setBuyerAddress(invoiceList.get("bankAddress"));
            newElecInvoiceInfoVO.setBuyerTelePhone(invoiceList.get("mobile"));
            newElecInvoiceInfoVO.setBuyerBankName(invoiceList.get("bankName"));
            newElecInvoiceInfoVO.setBuyerAccountCode(invoiceList.get("bankNo"));
            newElecInvoiceInfoVO.setNewElecPolicyInfoList(newElecPolicyInfoVOlist);
            newElecInvoiceInfoVOS.add(newElecInvoiceInfoVO);
            newElecInvoicePrintRequestVO.setNewElecInvoiceInfoList(newElecInvoiceInfoVOS);
            // 下载电子发票 拼装参数
            IssuePolicyLogEntity t = new IssuePolicyLogEntity();
            consumeStatus = "6";
            t.setApplicationFormCode(tbNo);
            t.setPolicyNo(policyNo);
            t.setType("3");
            t.setStatus(consumeStatus);
            t.setCreateTime(currentTime);
            t.setUpdateTime(currentTime);
            t.setProCode(proCode);
            t.setIfCode(ifCode);
            String param = JSON.toJSONString(newElecInvoicePrintRequestVO);
            t.setParam(param);
            t.setTimes(1);
            issuePolicyLogEntity.setIfCode(ifCode);
            // 电子发票的消费记录入库
            issuePolicyLogEntityMapper.insert(t);
            log.info(DateUtils.getCurrentTime() + "投保单号是" + tbNo + "发票申请开始，入参" + param);
            ResponseEntity<String> responseEntity = null;
            try {
                responseEntity = dexClient.text("edu", "202012091335240", "1.0", seqNo, param);
                log.info(DateUtils.getCurrentTime() + "投保单号是" + tbNo + "发票申请结束，回参" + responseEntity.getStatusCodeValue() + "," + responseEntity.getBody());
                if (responseEntity.getBody().equals("Effective")) {
                    //判断返回的是够是申请成功,如果开具成功Effective,自己拼接下载地址进行下载
                    String url = getGSInvoiceAddress(policyNo);
                    //根据地址下载电子发票
                    Map<String, String> invoiceMap = new HashMap<>();
                    invoiceMap.put("ApplicationFormCode", tbNo);
                    invoiceMap.put("url", url);
                    String invoiceParam = JsonUtils.toJson(invoiceMap);
                    log.info(DateUtils.getCurrentTime() + "投保单号是" + tbNo + "下载发票开始，入参" + invoiceParam);
                    responseEntity = dexClient.text("edu", "20190518021", "1.0", seqNo, invoiceParam);
                    log.info(DateUtils.getCurrentTime() + "投保单号是" + tbNo + "下载发票结束，回参" + responseEntity.getStatusCodeValue() + "," + responseEntity.getBody());
                    if (responseEntity != null) {
                        // 请求200，继续执行
                        if (responseEntity.getStatusCodeValue() != 200) {
                            log.error("请求下载电子发票失败");
                            t.setStatus("6");
                            t.setTimes(1);
                            t.setUpdateTime(currentTime);
                            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                        } else {
                            String ebody = responseEntity.getBody();
                            doc = DocumentHelper.parseText(ebody);
                            Element ebodyElement = doc.getRootElement();
                            String code = ebodyElement.element("code").getStringValue();
                            if ("0000".equals(code)) {
                                String eInvoiceId = ebodyElement.element("data").getStringValue();
                                t.setStatus("2");
                                t.setEInvoiceId(eInvoiceId);
                                t.setTimes(1);
                                bindInvoice(t.getApplicationFormCode(), eInvoiceId, t);
                                log.info("国寿电子发票 下载消息 fileId ：{}", eInvoiceId);
                            } else {
                                t.setStatus("6");
                                t.setTimes(1);
                                t.setUpdateTime(currentTime);
                                issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error("调用dex服务失败,请重试");
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     * 绑定发票资源，更新下载状态
     *
     * @param applicationFormCode 投保单号
     * @param fileId              文件id
     */
    private void bindInvoice(String applicationFormCode, String fileId, IssuePolicyLogEntity issuePolicyLogEntity) throws Exception {
        String status = issuePolicyLogEntity.getStatus();
        ResBindQo resBindQo = new ResBindQo();
        resBindQo.setApplicationFormCode(applicationFormCode);
        ResBindDetailQo resBindDetailQo = new ResBindDetailQo();
        resBindDetailQo.setBizCodeType("02");// todo 电子发票应该写什么？？？  王立波 02
        resBindDetailQo.setResCode("P001");
        resBindDetailQo.setResId(fileId);
        resBindDetailQo.setResName("电子发票");
        List<ResBindDetailQo> list = new ArrayList<>();
        list.add(resBindDetailQo);
        resBindQo.setDetailList(list);
        ResponseEntity<GenericListResponse<Map<String, String>>> genericListResponseResponseEntity = null;
        genericListResponseResponseEntity = insClient.bindResources(resBindQo);
        GenericListResponse<Map<String, String>> body = genericListResponseResponseEntity.getBody();
        String code = body.getCode();
        log.info(DateUtils.getCurrentTime() + "调用绑定资源接口返回结果码" + code + ":" + body.getMsg());
        if (!"0000".equals(code)) {
            issuePolicyLogEntity.setTimes(1);
            issuePolicyLogEntity.setEPolicyId(fileId);
            issuePolicyLogEntity.setStatus("6");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(issuePolicyLogEntity);
        } else {
            issuePolicyLogEntity.setTimes(1);
            issuePolicyLogEntity.setEPolicyId(fileId);
            issuePolicyLogEntity.setStatus("2");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(issuePolicyLogEntity);
        }

    }

    /*
     * 绑定资源，更新下载状态
     * @param applicationFormCode 投保单号
     * @param fileId             文件id
     */
    private void bindingResources(String applicationFormCode, String fileId, IssuePolicyLogEntity issuePolicyLogEntity) throws Exception {
        String status = issuePolicyLogEntity.getStatus();
        if ("3".equals(status)) {
            issuePolicyLogEntity.setTimes(1);
            issuePolicyLogEntity.setEPolicyId(fileId);
            issuePolicyLogEntity.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(issuePolicyLogEntity);
        } else {
            ResBindQo resBindQo = new ResBindQo();
            resBindQo.setApplicationFormCode(applicationFormCode);
            ResBindDetailQo resBindDetailQo = new ResBindDetailQo();
            resBindDetailQo.setBizCodeType("01");
            resBindDetailQo.setResCode("A002");
            resBindDetailQo.setResId(fileId);
            resBindDetailQo.setResName("电子保单、保单影印件");
            List<ResBindDetailQo> list = new ArrayList<>();
            list.add(resBindDetailQo);
            resBindQo.setDetailList(list);
            ResponseEntity<GenericListResponse<Map<String, String>>> genericListResponseResponseEntity = null;
            try {
                String s = JsonUtils.toJson(resBindQo);
                log.info(DateUtils.getCurrentTime() + "投保单号 " + applicationFormCode + " 调用绑定资源接口开始，入参：" + s);
                genericListResponseResponseEntity = insClient.bindResources(resBindQo);
                GenericListResponse<Map<String, String>> body = genericListResponseResponseEntity.getBody();
                String code = body.getCode();
                log.info(DateUtils.getCurrentTime() + "投保单号 " + applicationFormCode + " 调用绑定资源接口返回结果码" + code + ":" + body.getMsg());
                if (!"0000".equals(code)) {
                    issuePolicyLogEntity.setTimes(1);
                    issuePolicyLogEntity.setEPolicyId(fileId);
                    issuePolicyLogEntity.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(issuePolicyLogEntity);
                } else {
                    issuePolicyLogEntity.setTimes(1);
                    issuePolicyLogEntity.setEPolicyId(fileId);
                    issuePolicyLogEntity.setStatus("2");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(issuePolicyLogEntity);
                }
            } catch (Exception e) {
                issuePolicyLogEntity.setTimes(1);
                issuePolicyLogEntity.setEPolicyId(fileId);
                issuePolicyLogEntity.setStatus("3");
                issuePolicyLogEntityMapper.updateByPrimaryKeySelective(issuePolicyLogEntity);
                log.error("调用绑定资源接口失败，请重新尝试");
            }
        }
    }

    /**
     * 统一带url的电子保单下载及绑定资源
     * 需要数据交换中心返回的报文中添加
     * 【公司编码companyCode】
     * 【电子保单地址url】
     * 【投保成功标识ResponseCode(0000)】
     *
     * @param rootElement
     * @return
     */
    private Boolean processEpolicy(Element rootElement, IssueEnum issueEnum) {
        // 解析xml，封装数据
        Element reqPacket = getReqPacket(rootElement);
        Element respPacket = getRespPacket(rootElement);
        String proCode = issueEnum.getProCode();
        String currentTime = DateUtils.getCurrentTime();
        // 投保单号
        String tbNo = rootElement.element("ApplicationFormCode").getStringValue();
        // 保单号
        String policyNo = rootElement.element("PolicyNo").getStringValue();
        //出单公司编码
        String companyCode = rootElement.element("companyCode").getStringValue();
        // 入库
        // 入库之前首先判断 是否已经入库  根据投保单号判断
        IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
        issueRecordEntity.setApplicationFormCode(tbNo);
        List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
        if (select != null && select.size() > 0) {
            log.info("系统时间：{}, {}投保单号是 {} 的消息发送重复", issueEnum.getDesc(), currentTime, tbNo);
            // 消息重复，消息直接消费完成。
            return true;
        }
        issueRecordEntity.setPolicyNo(policyNo);
        issueRecordEntity.setCompanyCode(companyCode);
        issueRecordEntity.setProCode(proCode);
        issueRecordEntity.setReqPacket(reqPacket.asXML());
        issueRecordEntity.setResPacket(respPacket.asXML());
        issueRecordEntity.setSendStatus("1");
        String status = rootElement.element("ResponseCode").getStringValue();
        if ("0000".equals(status)) {
            status = "2";
        } else {
            status = "3";
        }
        // 数据中心返回 的投保单状态
        issueRecordEntity.setStatus(status);
        issueRecordEntity.setCreateTime(currentTime);
        issueRecordEntity.setUpdateTime(currentTime);
        issueRecordEntity.setIfCode(issueEnum.getIfCode());
        issueRecordEntityMapper.insert(issueRecordEntity);
        if ("3".equals(status)) {
            // 出单失败，消息直接消费完成，在入库的逻辑后边。
            return true;
        }
        // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子保单
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";
        issuePolicyLogEntity.setApplicationFormCode(tbNo);
        issuePolicyLogEntity.setPolicyNo(policyNo);
        issuePolicyLogEntity.setType("1");
        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(proCode);
        String url = rootElement.element("url").getStringValue();
        log.info("{}电子保单地址{}", issueEnum.getDesc(), url);
        // 拼装下载报文
        Document doc = DocumentHelper.createDocument();
        Element info = doc.addElement("body");
        info.addElement("url").addText(url);
        issuePolicyLogEntity.setParam(info.asXML());
        issuePolicyLogEntity.setTimes(0);
        issuePolicyLogEntity.setIfCode(issueEnum.getIfCode());
        issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
        // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
        issueRecordEntity.setSendStatus("2");
        issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);
        //调用接口,请求数据交换中心，下载电子保单
        try {
            String eUrl = info.asXML().replace("&amp;", "&");
            log.info("{}的投保单号是 {}, 保单下载参数：{}", issueEnum.getDesc(), tbNo, eUrl);
            // 请求下载保单，成功更新
            String seqNo = Long.toString(Math.abs(new Random().nextLong()));
            ResponseEntity<String> responseEntity = dexClient.text("edu", "20190516022", "1.0", seqNo, eUrl);
            if (null == responseEntity) {
                log.info("{}的投保单号是 {}, 保单下载失败", issueEnum.getDesc(), tbNo);
                return false;
            }
            log.info("{}的投保单号是 {}, 保单下载返回值：{}, {}", issueEnum.getDesc(), tbNo, responseEntity.getStatusCodeValue(), responseEntity.getBody());
            consumeStatus = "2";
            String fileId = responseEntity.getBody();
            issuePolicyLogEntity.setStatus(consumeStatus);
            // 下载成功，更新数据库，绑定资源
            log.info(" 下载消息 fileId ：{}", issueEnum.getDesc(), fileId);
            bindingResources(tbNo, fileId, issuePolicyLogEntity);
            return true;
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 【新实责校责  阳光】
     *
     * @param rootElement
     * @return
     */
    private Boolean processXSZAndXZ(Element rootElement, String ifCode) {
        Element reqPacket = getReqPacket(rootElement);
        Element respPacket = getRespPacket(rootElement);

        Element Body = reqPacket.element("Body");// 学责 ，实责/校责
        String companyCode = reqPacket.element("Head").element("UserId").getStringValue();
        String policyType = reqPacket.element("Body").element("Apply").element("PolicyType").getStringValue();

        String proCode = IssueEnum.getProCodeByIfCode(ifCode.concat(policyType));

        String mainTypeStr = "";
        String currentTime = DateUtils.getCurrentTime();
        Iterator iterator = respPacket.element("Body").elementIterator("Apply");

        // 首先获取地区
        // 只有山西地区  有发票
        Iterator iteratorReq = reqPacket.element("Body").elementIterator("Apply");

        // 投保单号和出单地区 组装的map
        Map<String, String> map = new HashMap();
        Map<String, String> taxMap = new HashMap();
        Map<String, String> mainTypeMap = new HashMap();
        Map<String, String> proCodeMap = new HashMap();
        while (iteratorReq.hasNext()) {
            Element nextReq = (Element) iteratorReq.next();
            String tbNo = nextReq.element("ApplyId").getStringValue();
            String issuingCompanyId = nextReq.element("IssuingCompanyId").getStringValue();
            String OrganizationCode = nextReq.element("PolicyHolder").element("OrganizationCode").getStringValue();

            String mainType = nextReq.element("MainType").getStringValue();

            // 学责
            proCode = nextReq.element("PolicyType").getStringValue();

            mainTypeMap.put(tbNo, mainType);
            proCodeMap.put(tbNo, proCode);
            taxMap.put(tbNo, OrganizationCode);
            map.put(tbNo, issuingCompanyId);
        }
        int size = map.size();// 请求体的集合和响应体的集合 size相等
        int i = 0;
        while (iterator.hasNext()) {
            Element nextResp = (Element) iterator.next();
            // 投保单号
            String tbNo = nextResp.element("ApplyId").getStringValue();
            // 保单号
            String policyNo = nextResp.element("PolicyNo").getStringValue();
            String fee = nextResp.element("Fee").getStringValue();
            proCode = proCodeMap.get(tbNo);
            mainTypeStr = mainTypeMap.get(tbNo);

            // 入库
            // 入库之前首先判断 是否已经入库  根据投保单号判断
            IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
            issueRecordEntity.setApplicationFormCode(tbNo);
            List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
            if (select == null || select.size() == 0) {
                issueRecordEntity.setPolicyNo(policyNo);
                issueRecordEntity.setCompanyCode(companyCode);
                issueRecordEntity.setProCode(proCode);
                issueRecordEntity.setReqPacket(reqPacket.asXML());
                issueRecordEntity.setResPacket(respPacket.asXML());
                issueRecordEntity.setSendStatus("1");
                issueRecordEntity.setMainType(mainTypeStr);
                String status = respPacket.element("Head").element("ResponseCode").getStringValue();

                if ("0".equals(status)) {
                    status = "2";
                } else {
                    status = "3";
                }
                // 数据中心返回 的投保单状态
                issueRecordEntity.setStatus(status);
                issueRecordEntity.setCreateTime(currentTime);
                issueRecordEntity.setUpdateTime(currentTime);
                issueRecordEntity.setIfCode(ifCode);
                issueRecordEntityMapper.insert(issueRecordEntity);

                if ("2".equals(status)) { // 成功
                    // 消费  ： 需要组织报文，去调用接口
                    IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
                    String consumeStatus = "1";
                    issuePolicyLogEntity.setApplicationFormCode(tbNo);
                    issuePolicyLogEntity.setPolicyNo(policyNo);
                    issuePolicyLogEntity.setType("1");
                    issuePolicyLogEntity.setStatus(consumeStatus);
                    issuePolicyLogEntity.setCreateTime(currentTime);
                    issuePolicyLogEntity.setUpdateTime(currentTime);
                    issuePolicyLogEntity.setProCode(proCode);
                    // 组装报文
                    Document doc = DocumentHelper.createDocument();
                    Element info = doc.addElement("INSURENCEINFO");
                    info.addElement("POLICYNO").addText(policyNo);
                    issuePolicyLogEntity.setParam(info.asXML());
                    issuePolicyLogEntity.setMainType(mainTypeStr);
                    issuePolicyLogEntity.setTimes(0);
                    issuePolicyLogEntity.setIfCode(ifCode);
                    issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
                    // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
                    issueRecordEntity.setSendStatus("2");
                    issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);
                    try {
                        // 请求下载保单，成功更新
                        log.info(DateUtils.getCurrentTime() + "实责校责保单号是" + tbNo + "下载保单开始，入参" + info.asXML());
                        String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                        ResponseEntity<String> responseEntity = dexClient.text("edu", "20190726003", "1.0", seqNo, info.asXML());
                        consumeStatus = "2";
                        String ebody = responseEntity.getBody();
                        log.info(DateUtils.getCurrentTime() + "实责校责保单号是" + tbNo + "下载保单结束，回参" + responseEntity.getStatusCodeValue() + "," + ebody);
                        doc = DocumentHelper.parseText(ebody);
                        Element ebodyElement = doc.getRootElement();
                        Element data = ebodyElement.element("data");
                        if (data == null) {
                            log.error("实责校责请求下载电子保单失败");
                            consumeStatus = "3";
                        }
                        String fileId = data.getStringValue();
                        issuePolicyLogEntity.setStatus(consumeStatus);
                        // 下载电子保单成功，更新数据库，绑定资源
                        log.info("实责校责下载消息 fileId ：{}", fileId);
                        bindingResources(tbNo, fileId, issuePolicyLogEntity);
                        i++;

                    } catch (DocumentException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                        issuePolicyLogEntity.setTimes(1);
                        issuePolicyLogEntity.setStatus("3");
                        issuePolicyLogEntityMapper.updateByPrimaryKeySelective(issuePolicyLogEntity);
                    }
                } else {
                    status = "3";
                    i++;
                }
            } else {
                log.info("系统时间：" + currentTime + ",实责校责投保单号是" + tbNo + "的消息发送重复");
                i++;
            }
        }
        return true;
    }

    /**
     * 【食品  阳光】
     *
     * @param rootElement
     * @return
     */
    private Boolean processSP(Element rootElement, String ifCode) {
        Element reqPacket = getReqPacket(rootElement);
        Element respPacket = getRespPacket(rootElement);

        String currentTime = DateUtils.getCurrentTime();
        // 投保单号
        String tbNo = rootElement.element("ApplicationFormCode").getStringValue();
        // 保单号
        String policyNo = rootElement.element("PolicyNo").getStringValue();
        // 解析险种
        //String proCode = reqPacket.element("Body").element("Apply").element("PolicyType").getStringValue();
        String proCode = IssueEnum.getProCodeByIfCode(ifCode);

        log.debug("系统时间：{}, [食品险（阳光）]下载电子保单 投保单号：{},保单号：{},产品险种编码：{}", currentTime, tbNo, policyNo, proCode);
        // 入库
        // 入库之前首先判断 是否已经入库  根据投保单号判断
        IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
        issueRecordEntity.setApplicationFormCode(tbNo);
        List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
        if (select != null && select.size() > 0) {
            log.info("系统时间：{} ,食品险（阳光）投保单号是: {} 的消息发送重复", currentTime, tbNo);
            // 消息重复，消息直接消费完成。
            return true;
        }
        issueRecordEntity.setPolicyNo(policyNo);
        issueRecordEntity.setProCode(proCode);
        issueRecordEntity.setReqPacket(reqPacket.asXML());
        issueRecordEntity.setResPacket(respPacket.asXML());
        issueRecordEntity.setSendStatus("1");
        String status = respPacket.element("Head").element("ResponseCode").getStringValue();

        if ("0".equals(status)) {
            status = "2";
        } else {
            status = "3";
        }
        // 数据中心返回 的投保单状态
        issueRecordEntity.setStatus(status);
        issueRecordEntity.setCreateTime(currentTime);
        issueRecordEntity.setUpdateTime(currentTime);
        issueRecordEntity.setIfCode(ifCode);
        issueRecordEntityMapper.insert(issueRecordEntity);
        if ("3".equals(status)) {
            // 出单失败或者重复出单，消息直接消费完成，在入库的逻辑后边。
            return true;
        }
        // 消费  ： 需要组织报文，去调用接口
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";
        issuePolicyLogEntity.setApplicationFormCode(tbNo);
        issuePolicyLogEntity.setPolicyNo(policyNo);
        issuePolicyLogEntity.setType("1");
        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(proCode);
        // 组装报文
        Document doc = DocumentHelper.createDocument();
        Element info = doc.addElement("POLICYNO");
        info.addText(policyNo);
        issuePolicyLogEntity.setParam(info.asXML());
        issuePolicyLogEntity.setTimes(0);
        issuePolicyLogEntity.setIfCode(ifCode);
        issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
        // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
        issueRecordEntity.setSendStatus("2");
        issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);
        try {
            // 请求下载保单，成功更新
            log.info(DateUtils.getCurrentTime() + "阳光食品保单号是" + tbNo + "下载保单开始，入参" + info.asXML());
            String seqNo = Long.toString(Math.abs(new Random().nextLong()));
            ResponseEntity<String> responseEntity = dexClient.text("edu", "20190805003", "1.0", seqNo, info.asXML());
            consumeStatus = "2";
            String ebody = responseEntity.getBody();
            log.info(DateUtils.getCurrentTime() + "阳光食品保单号是" + tbNo + "下载保单结束，回参" + responseEntity.getStatusCodeValue() + "," + ebody);
            doc = DocumentHelper.parseText(ebody);
            Element ebodyElement = doc.getRootElement();
            Element data = ebodyElement.element("data");
            if (data == null) {
                log.error("阳光食品请求下载电子保单失败");
                consumeStatus = "3";
            }
            System.out.println("食品险电子保单获取到值" + data + "状态码-- " + consumeStatus);
            String fileId = data.getStringValue();
            issuePolicyLogEntity.setStatus(consumeStatus);
            // 下载电子保单成功，更新数据库，绑定资源
            log.info("阳光食品下载消息 fileId ：{}", fileId);
            bindingResources(tbNo, fileId, issuePolicyLogEntity);
            // 下载电子保单成功，更新数据库，绑定资源
            log.info("实责校责下载消息 fileId ：{}", fileId);
            //获取到地区编码，只有山西地区可以下载发票
            String issuingCompanyId = reqPacket.element("Body").element("Apply").element("InsureComp").element("IssuingCompanyId").getStringValue();
            Map<String, String> invoiceList = getAppcodeInvoiceType(tbNo);
            String fee = respPacket.element("Body").element("Apply").element("Fee").getStringValue();
            //食品山西，金额小于10w默认开具电子发票，别的地区选择电子发票就去开，纸质发票不去开具，金额大于10w元的也不去开具
            if (("301400".equals(issuingCompanyId) && judgingTheAmount(fee)) || (invoiceList.get("invoiceType").equals(InvoiceTypeEnum.ELECTRONIC_INVOICE.getType()) && judgingTheAmount(fee))) { // 有发票
                // 下载电子发票 拼装参数
                IssuePolicyLogEntity t = new IssuePolicyLogEntity();
                consumeStatus = "1";
                t.setApplicationFormCode(tbNo);
                t.setPolicyNo(policyNo);
                t.setType("3");
                t.setStatus(consumeStatus);
                t.setCreateTime(currentTime);
                t.setUpdateTime(currentTime);
                t.setProCode(proCode);
                t.setMainType("3");
                doc = DocumentHelper.createDocument();
                // 组装电子发票的报文
                String serialNo = respPacket.element("Body").element("Apply").element("ApplyId").getStringValue();
                String taxpayerNo = reqPacket.element("Body").element("Apply").element("HolderInfo").element("OrganizationCode").getStringValue();
                info = doc.addElement("INSURENCEINFO");
                doc.setRootElement(info);

                Element policylist = info.addElement("POLICYLIST");
                Element ismerge = policylist.addElement("ISMERGE");
                ismerge.addText("0");
                Element POLICYINFO = policylist.addElement("POLICYINFO");
                Element productcode = POLICYINFO.addElement("PRODUCTCODE");
                productcode.addText("160301");
                POLICYINFO.addElement("SERIALNO").addText(serialNo);
                POLICYINFO.addElement("POLICYNO").addText(policyNo);
                POLICYINFO.addElement("INVOICETYPE").addText("2");
                //新增购方信息
                String bankAddress = invoiceList.get("bankAddress");
                String mobile = invoiceList.get("mobile");
                String bankName = invoiceList.get("bankName");
                String bankNo = invoiceList.get("bankNo");
                String taxpayerIdentificationNumber = invoiceList.get("taxpayerIdentificationNumber");
                POLICYINFO.addElement("TAXPAYERNO").addText(StringUtils.isEmpty(taxpayerIdentificationNumber) ? taxpayerNo : taxpayerIdentificationNumber);
                POLICYINFO.addElement("BANKADDRESS").addText(StringUtils.isEmpty(bankAddress) ? "" : bankAddress);
                POLICYINFO.addElement("MOBILE").addText(StringUtils.isEmpty(mobile) ? "" : mobile);
                POLICYINFO.addElement("BANKNAME").addText(StringUtils.isEmpty(bankName) ? "" : bankName);
                POLICYINFO.addElement("BANKNO").addText(StringUtils.isEmpty(bankNo) ? "" : bankNo);
                Element AMOUNT = policylist.addElement("AMOUNT");
                AMOUNT.addText("1");
                Element TOTALJYJE = policylist.addElement("TOTALJYJE");
                TOTALJYJE.addText(fee);
                t.setParam(info.asXML());
                t.setTimes(0);
                t.setIfCode(ifCode);
                // 电子发票的消费记录入库
                issuePolicyLogEntityMapper.insert(t);
                // 刘高逻辑：直接去下载即可。
                log.info(DateUtils.getCurrentTime() + "阳光食品险投保单号是" + tbNo + "下载发票开始，入参" + info.asXML());
                seqNo = Long.toString(Math.abs(new Random().nextLong()));
                responseEntity = dexClient.text("edu", "20190826044", "1.0", seqNo, info.asXML());
                log.info(DateUtils.getCurrentTime() + "阳光食品险投保单号是" + tbNo + "下载发票结束，回参" + responseEntity.getStatusCodeValue() + "," + responseEntity.getBody());
                // 请求200，继续执行
                log.info("阳光食品险的投保单号是 {}, 保单下载返回值：{}, {}", tbNo, responseEntity.getStatusCodeValue(), responseEntity.getBody());
                consumeStatus = "2";
                if (StringUtil.isNotEmpty(responseEntity.getBody())) {
                    issuePolicyLogEntity.setStatus(consumeStatus);
                    String invoiceFileId = responseEntity.getBody();
                    // 下载成功，更新数据库，绑定资源
                    log.info("阳光食品险 下载消息 invoiceFileId ：{}", invoiceFileId);
                    t.setStatus("2");
                    t.setTimes(1);
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    log.error("阳光食品险请求下载电子发票失败");
                    t.setStatus("6");
                    t.setTimes(1);
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                }
            }
            return true;
        } catch (Exception e) {
            // 下载电子发票 拼装参数
            downInvoice(ifCode, reqPacket, respPacket, currentTime, tbNo, policyNo, proCode);
            e.printStackTrace();
            issuePolicyLogEntity.setTimes(1);
            issuePolicyLogEntity.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(issuePolicyLogEntity);
        }
        sendEmail(tbNo, "21");
        return true;
    }

    private void downInvoice(String ifCode, Element reqPacket, Element respPacket, String currentTime, String tbNo, String policyNo, String proCode) {
        String consumeStatus;
        Document doc;
        Element info;
        IssuePolicyLogEntity t = new IssuePolicyLogEntity();
        consumeStatus = "1";
        t.setApplicationFormCode(tbNo);
        t.setPolicyNo(policyNo);
        t.setType("3");
        t.setStatus(consumeStatus);
        t.setCreateTime(currentTime);
        t.setUpdateTime(currentTime);
        t.setProCode(proCode);
        t.setMainType("3");
        doc = DocumentHelper.createDocument();
        // 组装电子发票的报文
        String serialNo = respPacket.element("Body").element("Apply").element("ApplyId").getStringValue();
        String taxpayerNo = reqPacket.element("Body").element("Apply").element("HolderInfo").element("OrganizationCode").getStringValue();
        info = doc.addElement("INSURENCEINFO");
        doc.setRootElement(info);

        Element policylist = info.addElement("POLICYLIST");
        Element ismerge = policylist.addElement("ISMERGE");
        ismerge.addText("0");
        Element POLICYINFO = policylist.addElement("POLICYINFO");
        Element productcode = POLICYINFO.addElement("PRODUCTCODE");
        productcode.addText("160301");
        String fee = respPacket.element("Body").element("Apply").element("Fee").getStringValue();
        POLICYINFO.addElement("SERIALNO").addText(serialNo);
        POLICYINFO.addElement("POLICYNO").addText(policyNo);
        POLICYINFO.addElement("INVOICETYPE").addText("2");
        POLICYINFO.addElement("TAXPAYERNO").addText(taxpayerNo);
        Element AMOUNT = policylist.addElement("AMOUNT");
        AMOUNT.addText("1");
        Element TOTALJYJE = policylist.addElement("TOTALJYJE");
        TOTALJYJE.addText(fee);
        t.setParam(info.asXML());
        t.setTimes(0);
        t.setIfCode(ifCode);
        // 电子发票的消费记录入库
        issuePolicyLogEntityMapper.insert(t);
    }

    /*
     * 解析返回响应报文xml
     * @param document 文档对象
     * @return 返回dom元素
     */
    public Element getRespPacket(Element rootElement) {
        Element respPacket = rootElement.element("respPacket");
        Element element = null;
        if (respPacket != null) {
            try {
                element = DocumentHelper.parseText(respPacket.getText()).getRootElement();
            } catch (DocumentException e) {
                e.printStackTrace();
                log.error("xml转义失败，生成xml错误", e);
            }
        }
        return element;
    }

    /*
     * 解析返回请求报文xml
     * @param document 文档对象
     * @return 返回dom元素
     */
    public Element getReqPacket(Element rootElement) {
        Element respPacket = rootElement.element("reqPacket");
        Element element = null;
        if (respPacket != null) {
            try {
                element = DocumentHelper.parseText(respPacket.getText()).getRootElement();
            } catch (DocumentException e) {
                e.printStackTrace();
                log.error("xml转义失败，生成xml错误", e);
            }
        }
        return element;
    }

    public Element analysisXmlStrToReq(String xmlStr) {
        xmlStr = xmlStr.replace("&lt;", "<");
        xmlStr = xmlStr.replace("&gt;", ">");
        xmlStr = xmlStr.replace("&#13;", "");
        Element reqPacket = null;
        try {
            Document doc = DocumentHelper.parseText(xmlStr);
            Element rootElement = doc.getRootElement();
            reqPacket = rootElement.element("reqPacket");
        } catch (DocumentException e) {
            e.printStackTrace();
            log.error("xml转义失败，生成xml错误", e);
        }
        return reqPacket;
    }

    public Element analysisXmlStrToResp(String xmlStr) {
        xmlStr = xmlStr.replace("&lt;", "<");
        xmlStr = xmlStr.replace("&gt;", ">");
        xmlStr = xmlStr.replace("&#13;", "");
        Element respPacket = null;
        try {
            Document doc = DocumentHelper.parseText(xmlStr);
            Element rootElement = doc.getRootElement();
            respPacket = rootElement.element("respPacket");
        } catch (DocumentException e) {
            e.printStackTrace();
            log.error("xml转义失败，生成xml错误", e);
        }
        return respPacket;
    }

    /**
     * 广东校责、教职工、食品、校车
     *
     * @param rootElement
     * @return
     */
    private Boolean processGD(Element rootElement, String ifCode) {

        String findCode = "processGD_" + System.currentTimeMillis();

        // 解析xml，封装数据
        Element reqPacket = getReqPacket(rootElement);
        Element respPacket = getRespPacket(rootElement);

        String proCode = IssueEnum.getProCodeByIfCode(ifCode);

        String currentTime = DateUtils.getCurrentTime();
        // 投保单号
        String tbNo = rootElement.element("ApplicationFormCode").getStringValue();
        // 保单号
        String policyNo = rootElement.element("PolicyNo").getStringValue();
        // 保险公司编码
        String companyCode = rootElement.element("CompanyCode").getStringValue();
        // 入库
        // 入库之前首先判断 是否已经入库  根据投保单号判断
        IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
        issueRecordEntity.setApplicationFormCode(tbNo);
        List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
        if (select != null && select.size() > 0) {
            log.info("{} 广东校责、食品、教职工、校车投保单号是 {} 的消息发送重复", findCode, tbNo);
            // 消息重复，消息直接消费完成。
            return true;
        }
        issueRecordEntity.setPolicyNo(policyNo);
        issueRecordEntity.setCompanyCode(companyCode);
        issueRecordEntity.setProCode(proCode);
        issueRecordEntity.setReqPacket(reqPacket.asXML());
        issueRecordEntity.setResPacket(respPacket.asXML());
        issueRecordEntity.setSendStatus("1");
        String status = respPacket.element("head").element("responseCompleteMessageStatus").element("messageStatusCode").getStringValue();
        if ("000000".equals(status)) {
            status = "2";
        } else {
            status = "3";
        }
        // 数据中心返回 的投保单状态
        issueRecordEntity.setStatus(status);
        issueRecordEntity.setCreateTime(currentTime);
        issueRecordEntity.setUpdateTime(currentTime);
        issueRecordEntity.setIfCode(ifCode);
        issueRecordEntityMapper.insert(issueRecordEntity);
        if ("3".equals(status)) {
            // 出单失败，消息直接消费完成，在入库的逻辑后边。
            return true;
        }
        // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子保单
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";
        issuePolicyLogEntity.setApplicationFormCode(tbNo);
        issuePolicyLogEntity.setPolicyNo(policyNo);
        issuePolicyLogEntity.setType("1");
        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(proCode);
        // 拼装下载报文
        Document doc = DocumentHelper.createDocument();
        Element message = doc.addElement("Message");
        message.addElement("PolicyNo").addText(policyNo);
        issuePolicyLogEntity.setParam(message.asXML());
        issuePolicyLogEntity.setTimes(0);
        issuePolicyLogEntity.setIfCode(ifCode);
        issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
        // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
        issueRecordEntity.setSendStatus("2");
        issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);
        //调用接口,请求数据交换中心，下载电子保单
        try {
            log.info("{} 广东校责、食品、教职工、校车的投保单号是 {}, 电子保单下载参数：{}", findCode, tbNo, message.asXML());
            // 请求下载保单，成功更新
            String seqNo = Long.toString(Math.abs(new Random().nextLong()));
            ResponseEntity<String> responseEntity = dexClient.text("edu", "202008181525000", "1.0", seqNo, message.asXML());
            log.info("{} 广东校责、食品、教职工、校车的投保单号是 {}, 电子保单下载返回值：{}, {}", findCode, tbNo, responseEntity.getStatusCodeValue(), responseEntity.getBody());
            String fileId = responseEntity.getBody();
            if (StringUtils.isNotBlank(fileId)) {
                consumeStatus = "2";
                issuePolicyLogEntity.setStatus(consumeStatus);
                // 下载成功，更新数据库，绑定资源
                log.info("{} 广东校责、食品、教职工、校车 下载消息 fileId ：{}", findCode, fileId);
                bindingResources(tbNo, fileId, issuePolicyLogEntity);

                log.info("{} 广东校责、食品、教职工、校车 电子保单下载成功，开始发送邮件", findCode);
                sendEmailGD(tbNo, "021");
            } else {
                consumeStatus = "3";
                issuePolicyLogEntity.setStatus(consumeStatus);
                // 下载失败，更新数据库，绑定资源
                log.info("{} 广东校责、食品、教职工、校车 下载消息 fileId ：{}", findCode, fileId);
                bindingResources(tbNo, fileId, issuePolicyLogEntity);
            }

            String elecInvoiceFlag = reqPacket.element("body").element("entity").element("elcPolicy").element("isEInvoiceFlag").getStringValue();
            log.info("{} 广东校责、食品、教职工、校车 投保单号 {} ，电子发票标识 {}", findCode, tbNo, elecInvoiceFlag);

            //获取电子发票 1-表示开电子票
            if (StringUtils.isNotBlank(elecInvoiceFlag) && "1".equals(elecInvoiceFlag)) { // 有发票
                log.info("{} 广东校责、食品、教职工、校车 投保单号 {} 下载电子发票开始", findCode, tbNo);
                //todo 9-3 17:17
                // 下载电子发票 拼装参数
                IssuePolicyLogEntity t = new IssuePolicyLogEntity();
                consumeStatus = "6";
                t.setApplicationFormCode(tbNo);
                t.setPolicyNo(policyNo);
                t.setType("3");
                t.setStatus(consumeStatus);
                t.setCreateTime(currentTime);
                t.setUpdateTime(currentTime);
                t.setProCode(proCode);
                t.setIfCode(ifCode);
                // 组装电子发票的报文  电子保单与电子发票报文一致
                t.setParam(message.asXML());
                t.setTimes(1);
                issuePolicyLogEntity.setIfCode(ifCode);
                // 电子发票的消费记录入库
                issuePolicyLogEntityMapper.insert(t);
                log.info("{} 广东校责、食品、教职工、校车 投保单号是 {} 下载发票入参{}", findCode, tbNo, message.asXML());
                String invoiceSeqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> invoiceResponseEntity = null;
                try {
                    invoiceResponseEntity = dexClient.text("edu", "202009031726310", "1.0", invoiceSeqNo, message.asXML());
                    log.info("{} 广东校责、食品、教职工、校车 投保单号是 {} 下载发票结束，回参{}", findCode, tbNo, invoiceResponseEntity.getStatusCodeValue() + "," + invoiceResponseEntity.getBody());
                    if (invoiceResponseEntity != null) {
                        // 请求200，继续执行
                        if (invoiceResponseEntity.getStatusCodeValue() != 200
                                || StringUtils.isBlank(invoiceResponseEntity.getBody())) {
                            log.error("{} 广东校责、食品、教职工、校车 投保单号是 {} 请求下载电子发票失败", findCode, tbNo);
                            t.setStatus("6");
                            t.setTimes(1);
                            t.setUpdateTime(currentTime);
                            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                        } else {
                            String invoiceFileId = invoiceResponseEntity.getBody();
                            t.setStatus("2");
                            t.setUpdateTime(currentTime);
                            t.setEInvoiceId(invoiceFileId);
                            // 下载成功，更新数据库，绑定资源
                            log.info("{} 广东校责、食品、教职工、校车 电子发票 下载消息 invoiceFileId ：{}", findCode, invoiceFileId);
                            bindInvoice(tbNo, invoiceFileId, t);

                            log.info("{} 广东校责、食品、教职工、校车 电子发票下载成功，开始发送邮件", findCode);
                            sendInvoiceEmailGD(tbNo, "23");
                        }
                    }
                } catch (Exception e) {
                    log.error("{} 广东校责、食品、教职工、校车 电子发票 调用dex服务失败,请重试", findCode);
                    e.printStackTrace();
                }
            }

            return true;
        } catch (DocumentException e) {
            e.printStackTrace();
            log.info("{} 广东校责、食品、教职工、校车的投保单号是 {}，电子保单下载异常", findCode, tbNo);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("{} 广东校责、食品、教职工、校车的投保单号是 {}，电子保单下载异常", findCode, tbNo);
        }


        return false;
    }

    /**
     * 济宁学平险（线下批量录单）
     *
     * @param rootElement
     * @return
     */
    private Boolean processJiNingXPX(Element rootElement, String ifCode) {
        Element respPacket = getRespPacket(rootElement);
        Element reqPacket = getReqPacket(rootElement);

        String currentTime = DateUtils.getCurrentTime();
        // 投保单号
        String tbNo = rootElement.element("ApplicationFormCode").getStringValue();
        // 保单号
        String policyNo = rootElement.element("PolicyNo").getStringValue();
        // 电子保单下载
        String elecUrl = rootElement.element("ElecUrl").getStringValue();

        //String proCode = "19PR979745";
        String proCode = IssueEnum.getProCodeByIfCode(ifCode);

        log.debug("系统时间：{}, [济宁学平险]下载电子保单 投保单号：{},保单号：{},产品险种编码：{}", currentTime, tbNo, policyNo, proCode);
        // 入库
        // 入库之前首先判断 是否已经入库  根据投保单号判断
        IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
        issueRecordEntity.setApplicationFormCode(tbNo);
        List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
        if (select != null && select.size() > 0) {
            log.info("系统时间：{} ,济宁学平险投保单号是: {} 的消息发送重复", currentTime, tbNo);
            // 消息重复，消息直接消费完成。
            return true;
        }
        issueRecordEntity.setPolicyNo(policyNo);
        issueRecordEntity.setProCode(proCode);
        issueRecordEntity.setReqPacket(reqPacket.asXML());
        issueRecordEntity.setResPacket(respPacket.asXML());
        issueRecordEntity.setSendStatus("1");

        //9200：成功  其余：失败
        String status = respPacket.element("responsehead").element("responseCode").getStringValue();
        if ("9200".equals(status)) {
            status = "2";
        } else {
            status = "3";
        }
        // 数据中心返回 的投保单状态
        issueRecordEntity.setStatus(status);
        issueRecordEntity.setCreateTime(currentTime);
        issueRecordEntity.setUpdateTime(currentTime);
        issueRecordEntity.setIfCode(ifCode);
        issueRecordEntityMapper.insert(issueRecordEntity);
        if ("3".equals(status)) {
            // 出单失败或者重复出单，消息直接消费完成，在入库的逻辑后边。
            return true;
        }
        // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子保单
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";
        issuePolicyLogEntity.setApplicationFormCode(tbNo);
        issuePolicyLogEntity.setPolicyNo(policyNo);
        issuePolicyLogEntity.setType("1");
        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(proCode);

        //流水号
        String seqNo = Long.toString(Math.abs(new Random().nextLong()));

        // 拼装下载报文
        Document doc = DocumentHelper.createDocument();
        Element message = doc.addElement("message");
        message.addElement("url").addText(elecUrl);

        issuePolicyLogEntity.setParam(message.asXML());
        issuePolicyLogEntity.setTimes(0);
        issuePolicyLogEntity.setIfCode(ifCode);
        issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
        // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
        issueRecordEntity.setSendStatus("2");
        issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);

        //调用接口,请求数据交换中心，下载电子保单
        try {
            log.info("济宁学平险的投保单号是: {}, 保单下载参数：{}", tbNo, message.asXML());
            // 请求下载保单，成功更新
            ResponseEntity<String> responseEntity = dexClient.text("edu", "202008281553420", "1.0", seqNo, message.asXML());
            String fileId = responseEntity.getBody();
            log.info("济宁学平险的投保单号是: {}, 电子保单fileId返回值：{}, {}", tbNo, responseEntity.getStatusCodeValue(), fileId);

            consumeStatus = "2";
            if (StringUtils.isBlank(fileId)) {
                log.error("济宁学平险请求下载电子保单失败");
                consumeStatus = "3";
            }

            issuePolicyLogEntity.setStatus(consumeStatus);
            // 下载成功，更新数据库，绑定资源
            log.info("济宁学平险的投保单号是  下载消息 fileId：{}", fileId);
            bindingResources(tbNo, fileId, issuePolicyLogEntity);
            return true;
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 济宁学平险（线上）
     *
     * @param rootElement
     * @return
     */
    private Boolean processJiNingXPXOnline(Element rootElement, String ifCode) {
        Element respPacket = getRespPacket(rootElement);
        Element reqPacket = getReqPacket(rootElement);

        String currentTime = DateUtils.getCurrentTime();
        // 投保单号
        String tbNo = rootElement.element("ApplicationFormCode").getStringValue();
        // 保单号
        String policyNo = rootElement.element("PolicyNo").getStringValue();
        // 电子保单下载
        String elecUrl = rootElement.element("ElecUrl").getStringValue();

        //String proCode = "19PR979745";
        String proCode = IssueEnum.getProCodeByIfCode(ifCode);

        log.debug("系统时间：{}, [济宁学平险（线上）]下载电子保单 投保单号：{},保单号：{},产品险种编码：{}", currentTime, tbNo, policyNo, proCode);
        // 入库
        // 入库之前首先判断 是否已经入库  根据投保单号判断
        IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
        issueRecordEntity.setApplicationFormCode(tbNo);
        List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
        if (select != null && select.size() > 0) {
            log.info("系统时间：{} ,济宁学平险（线上）投保单号是: {} 的消息发送重复", currentTime, tbNo);
            // 消息重复，消息直接消费完成。
            return true;
        }
        issueRecordEntity.setPolicyNo(policyNo);
        issueRecordEntity.setProCode(proCode);
        issueRecordEntity.setReqPacket(reqPacket.asXML());
        issueRecordEntity.setResPacket(respPacket.asXML());
        issueRecordEntity.setSendStatus("1");

        //9200：成功  其余：失败
        String status = respPacket.element("responsehead").element("responseCode").getStringValue();
        if ("9200".equals(status)) {
            status = "2";
        } else {
            status = "3";
        }
        // 数据中心返回 的投保单状态
        issueRecordEntity.setStatus(status);
        issueRecordEntity.setCreateTime(currentTime);
        issueRecordEntity.setUpdateTime(currentTime);
        issueRecordEntity.setIfCode(ifCode);
        issueRecordEntityMapper.insert(issueRecordEntity);
        if ("3".equals(status)) {
            // 出单失败或者重复出单，消息直接消费完成，在入库的逻辑后边。
            return true;
        }
        // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子保单
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";
        issuePolicyLogEntity.setApplicationFormCode(tbNo);
        issuePolicyLogEntity.setPolicyNo(policyNo);
        issuePolicyLogEntity.setType("1");
        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(proCode);

        //流水号
        String seqNo = Long.toString(Math.abs(new Random().nextLong()));

        // 拼装下载报文
        Document doc = DocumentHelper.createDocument();
        Element message = doc.addElement("message");
        message.addElement("url").addText(elecUrl);

        issuePolicyLogEntity.setParam(message.asXML());
        issuePolicyLogEntity.setTimes(0);
        issuePolicyLogEntity.setIfCode(ifCode);
        issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
        // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
        issueRecordEntity.setSendStatus("2");
        issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);

        //调用接口,请求数据交换中心，下载电子保单
        try {
            log.info("济宁学平险（线上）的投保单号是: {}, 保单下载参数：{}", tbNo, message.asXML());
            // 请求下载保单，成功更新
            ResponseEntity<String> responseEntity = dexClient.text("edu", "202009090117050", "1.0", seqNo, message.asXML());
            String fileId = responseEntity.getBody();
            log.info("济宁学平险（线上）的投保单号是: {}, 电子保单fileId返回值：{}, {}", tbNo, responseEntity.getStatusCodeValue(), fileId);

            consumeStatus = "2";
            if (StringUtils.isBlank(fileId)) {
                log.error("济宁学平险（线上）请求下载电子保单失败");
                consumeStatus = "3";
            }

            issuePolicyLogEntity.setStatus(consumeStatus);
            // 下载成功，更新数据库，绑定资源
            log.info("济宁学平险（线上）的投保单号是  下载消息 fileId：{}", fileId);
            bindingResources(tbNo, fileId, issuePolicyLogEntity);
            return true;
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 启东学平险
     *
     * @param rootElement
     * @return
     */
    private Boolean processQiDong(Element rootElement, String ifCode) {
        String findCode = "processQiDong_" + System.currentTimeMillis();

        Element respPacket = getRespPacket(rootElement);
        Element reqPacket = getReqPacket(rootElement);

        String currentTime = DateUtils.getCurrentTime();
        // 投保单号
        String tbNo = rootElement.element("ApplicationFormCode").getStringValue();
        // 保单号
        String policyNo = rootElement.element("PolicyNo").getStringValue();
        // 电子保单下载
        String elecUrl = rootElement.element("ElecUrl").getStringValue();

        //String proCode = "19PR979745";
        String proCode = IssueEnum.getProCodeByIfCode(ifCode);

        log.debug("{} [启东学平险]下载电子保单 投保单号：{},保单号：{},产品险种编码：{}", findCode, tbNo, policyNo, proCode);
        // 入库
        // 入库之前首先判断 是否已经入库  根据投保单号判断
        IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
        issueRecordEntity.setApplicationFormCode(tbNo);
        List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
        if (select != null && select.size() > 0) {
            log.info("{} 启东学平险投保单号是: {} 的消息发送重复", findCode, tbNo);
            // 消息重复，消息直接消费完成。
            return true;
        }
        issueRecordEntity.setPolicyNo(policyNo);
        issueRecordEntity.setProCode(proCode);
        issueRecordEntity.setReqPacket(reqPacket.asXML());
        issueRecordEntity.setResPacket(respPacket.asXML());
        issueRecordEntity.setSendStatus("1");

        //9200：成功  其余：失败
        String status = "2";
        // 数据中心返回 的投保单状态
        issueRecordEntity.setStatus(status);
        issueRecordEntity.setCreateTime(currentTime);
        issueRecordEntity.setUpdateTime(currentTime);
        issueRecordEntity.setIfCode(ifCode);
        issueRecordEntityMapper.insert(issueRecordEntity);

        // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子保单
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";
        issuePolicyLogEntity.setApplicationFormCode(tbNo);
        issuePolicyLogEntity.setPolicyNo(policyNo);
        issuePolicyLogEntity.setType("1");
        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(proCode);

        //流水号
        String seqNo = Long.toString(Math.abs(new Random().nextLong()));

        // 拼装下载报文
        Document doc = DocumentHelper.createDocument();
        Element message = doc.addElement("message");
        message.addElement("url").addText(elecUrl);

        issuePolicyLogEntity.setParam(message.asXML());
        issuePolicyLogEntity.setTimes(0);
        issuePolicyLogEntity.setIfCode(ifCode);
        issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
        // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
        issueRecordEntity.setSendStatus("2");
        issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);

        //调用接口,请求数据交换中心，下载电子保单
        try {
            log.info("{} 启东学平险的投保单号是: {}, 保单下载参数：{}", findCode, tbNo, message.asXML());
            // 请求下载保单，成功更新
            ResponseEntity<String> responseEntity = dexClient.text("edu", "202009171808110", "1.0", seqNo, message.asXML());
            String fileId = responseEntity.getBody();
            log.info("{} 启东学平险的投保单号是: {}, 电子保单fileId返回值：{}, {}", findCode, tbNo, responseEntity.getStatusCodeValue(), fileId);

            consumeStatus = "2";
            if (StringUtils.isBlank(fileId)) {
                log.error("{} 启东学平险请求下载电子保单失败 fileId为空", findCode);
                consumeStatus = "3";
            }

            issuePolicyLogEntity.setStatus(consumeStatus);
            // 下载成功，更新数据库，绑定资源
            log.info("{} 启东学平险的投保单号是  下载消息 fileId：{}", findCode, fileId);
            bindingResources(tbNo, fileId, issuePolicyLogEntity);
            return true;
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
